Example usage for io.netty.channel ChannelOption TCP_NODELAY

List of usage examples for io.netty.channel ChannelOption TCP_NODELAY

Introduction

In this page you can find the example usage for io.netty.channel ChannelOption TCP_NODELAY.

Prototype

ChannelOption TCP_NODELAY

To view the source code for io.netty.channel ChannelOption TCP_NODELAY.

Click Source Link

Usage

From source file:org.opencloudb.config.model.SystemConfig.java

License:Open Source License

public void setSocketParams(AbstractBootstrap<?, ?> bootstrap, boolean isFrontChannel) throws IOException {
    int sorcvbuf = 0;
    int sosndbuf = 0;
    int soNoDelay = 0;
    if (isFrontChannel) {
        sorcvbuf = getFrontsocketsorcvbuf();
        sosndbuf = getFrontsocketsosndbuf();
        soNoDelay = getFrontSocketNoDelay();
    } else {/*from w w w. j a v  a  2  s.c  o  m*/
        sorcvbuf = getBacksocketsorcvbuf();
        sosndbuf = getBacksocketsosndbuf();
        soNoDelay = getBackSocketNoDelay();
    }

    bootstrap.option(ChannelOption.SO_RCVBUF, sorcvbuf);
    bootstrap.option(ChannelOption.SO_SNDBUF, sosndbuf);
    bootstrap.option(ChannelOption.TCP_NODELAY, soNoDelay == 1);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.option(ChannelOption.SO_REUSEADDR, true);
    bootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 1024 * 1024);
}

From source file:org.opendaylight.groupbasedpolicy.jsonrpc.RpcServer.java

License:Open Source License

public void start() {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*from  w  w w.j ava 2s .  com*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        logger.debug("New Passive channel created : " + ch.toString());
                        InetAddress address = ch.remoteAddress().getAddress();
                        int port = ch.remoteAddress().getPort();
                        String identifier = address.getHostAddress() + ":" + port;
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO), new JsonRpcDecoder(100000),
                                new StringEncoder(CharsetUtil.UTF_8));

                        handleNewConnection(identifier, ch);
                        logger.warn("Connected Node : " + identifier);
                    }
                });
        b.option(ChannelOption.TCP_NODELAY, true);
        b.option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(65535, 65535, 65535));
        // Start the server.
        ChannelFuture f = b.bind(identity, listenPort).sync();
        String id = f.channel().localAddress().toString();
        logger.warn("Connected Node : " + id);

        this.channel = f.channel();

        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
    } catch (InterruptedException e) {
        logger.error("Thread interrupted", e);
    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:org.opendaylight.ocpjava.protocol.impl.core.TcpHandler.java

License:Open Source License

/**
 * Starts server on selected port.//from w  ww .ja  va 2 s.c  o m
 */
@Override
public void run() {
    /*
     * We generally do not perform IO-unrelated tasks, so we want to have
     * all outstanding tasks completed before the executing thread goes
     * back into select.
     *
     * Any other setting means netty will measure the time it spent selecting
     * and spend roughly proportional time executing tasks.
     */
    workerGroup.setIoRatio(100);

    final ChannelFuture f;
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.DEBUG)).childHandler(channelInitializer)
                .option(ChannelOption.SO_BACKLOG, 128).option(ChannelOption.SO_REUSEADDR, true)
                //modify to "false" for OCP health-check
                .childOption(ChannelOption.SO_KEEPALIVE, false).childOption(ChannelOption.TCP_NODELAY, true)
                .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, DEFAULT_WRITE_HIGH_WATERMARK * 1024)
                .childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, DEFAULT_WRITE_LOW_WATERMARK * 1024)
                .childOption(ChannelOption.WRITE_SPIN_COUNT, DEFAULT_WRITE_SPIN_COUNT);

        if (startupAddress != null) {
            f = b.bind(startupAddress.getHostAddress(), port).sync();
        } else {
            f = b.bind(port).sync();
        }
    } catch (InterruptedException e) {
        LOG.error("Interrupted while binding port {}", port, e);
        return;
    }

    try {
        InetSocketAddress isa = (InetSocketAddress) f.channel().localAddress();
        address = isa.getHostString();

        // Update port, as it may have been specified as 0
        this.port = isa.getPort();

        LOG.debug("address from tcphandler: {}", address);
        isOnlineFuture.set(true);
        LOG.info("RadioHead listener started and ready to accept incoming tcp/tls connections on port: {}",
                port);
        f.channel().closeFuture().sync();
    } catch (InterruptedException e) {
        LOG.error("Interrupted while waiting for port {} shutdown", port, e);
    } finally {
        shutdown();
    }
}

From source file:org.opendaylight.ovsdb.lib.impl.OvsdbConnectionService.java

License:Open Source License

@Override
public OvsdbClient connectWithSsl(final InetAddress address, final int port, final SSLContext sslContext) {
    try {/*  w  w  w .  j  a v  a  2  s  . c  om*/
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(new NioEventLoopGroup());
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.option(ChannelOption.TCP_NODELAY, true);
        bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(65535, 65535, 65535));

        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel channel) throws Exception {
                if (sslContext != null) {
                    /* First add ssl handler if ssl context is given */
                    SSLEngine engine = sslContext.createSSLEngine(address.toString(), port);
                    engine.setUseClientMode(true);
                    channel.pipeline().addLast("ssl", new SslHandler(engine));
                }
                channel.pipeline().addLast(
                        //new LoggingHandler(LogLevel.INFO),
                        new JsonRpcDecoder(100000), new StringEncoder(CharsetUtil.UTF_8),
                        new ExceptionHandler());
            }
        });

        ChannelFuture future = bootstrap.connect(address, port).sync();
        Channel channel = future.channel();
        OvsdbClient client = getChannelClient(channel, ConnectionType.ACTIVE,
                Executors.newFixedThreadPool(NUM_THREADS));
        return client;
    } catch (InterruptedException e) {
        System.out.println("Thread was interrupted during connect");
    }
    return null;
}

From source file:org.opendaylight.ovsdb.lib.impl.OvsdbConnectionService.java

License:Open Source License

/**
 * OVSDB Passive listening thread that uses Netty ServerBootstrap to open
 * passive connection with Ssl and handle channel callbacks.
 *//*  w  ww  .ja  va 2s  .  c om*/
private static void ovsdbManagerWithSsl(int port, final SSLContext sslContext) {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel channel) throws Exception {
                        logger.debug("New Passive channel created : {}", channel);
                        if (sslContext != null) {
                            /* Add SSL handler first if SSL context is provided */
                            SSLEngine engine = sslContext.createSSLEngine();
                            engine.setUseClientMode(false); // work in a server mode
                            engine.setNeedClientAuth(true); // need client authentication
                            channel.pipeline().addLast("ssl", new SslHandler(engine));
                        }

                        channel.pipeline().addLast(new JsonRpcDecoder(100000),
                                new StringEncoder(CharsetUtil.UTF_8), new ExceptionHandler());

                        handleNewPassiveConnection(channel);
                    }
                });
        serverBootstrap.option(ChannelOption.TCP_NODELAY, true);
        serverBootstrap.option(ChannelOption.RCVBUF_ALLOCATOR,
                new AdaptiveRecvByteBufAllocator(65535, 65535, 65535));
        // Start the server.
        ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
        Channel serverListenChannel = channelFuture.channel();
        // Wait until the server socket is closed.
        serverListenChannel.closeFuture().sync();
    } catch (InterruptedException e) {
        logger.error("Thread interrupted", e);
    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:org.opendaylight.ovsdb.lib.jsonrpc.NettyBootStrapper.java

License:Open Source License

public ChannelFuture startServer(int localPort, final ChannelHandler... handlers) throws Exception {
    // Configure the server.
    bossGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup();
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100)
            .localAddress(localPort).childOption(ChannelOption.TCP_NODELAY, true)
            .childHandler(new ChannelInitializer<SocketChannel>() {

                @Override/*from  w  w w  .ja  v a2  s.co  m*/
                public void initChannel(SocketChannel ch) throws Exception {
                    for (ChannelHandler handler : handlers) {
                        ch.pipeline().addLast(handler);
                    }
                }
            });

    // Start the server.
    f = b.bind().sync();
    return f;
}

From source file:org.opendaylight.ovsdb.plugin.ConnectionService.java

License:Open Source License

@Override
public Node connect(String identifier, Map<ConnectionConstants, String> params) {
    InetAddress address;//from  w  w w.  j a  va 2  s . c  o m
    Integer port;

    try {
        address = InetAddress.getByName(params.get(ConnectionConstants.ADDRESS));
    } catch (Exception e) {
        logger.error("Unable to resolve " + params.get(ConnectionConstants.ADDRESS), e);
        return null;
    }

    try {
        port = Integer.parseInt(params.get(ConnectionConstants.PORT));
        if (port == 0)
            port = defaultOvsdbPort;
    } catch (Exception e) {
        port = defaultOvsdbPort;
    }

    try {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(new NioEventLoopGroup());
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.option(ChannelOption.TCP_NODELAY, true);
        bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(65535, 65535, 65535));

        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel channel) throws Exception {
                if (handlers == null) {
                    channel.pipeline().addLast(
                            //new LoggingHandler(LogLevel.INFO),
                            new JsonRpcDecoder(10000000), new StringEncoder(CharsetUtil.UTF_8));
                } else {
                    for (ChannelHandler handler : handlers) {
                        channel.pipeline().addLast(handler);
                    }
                }
            }
        });

        ChannelFuture future = bootstrap.connect(address, port).sync();
        Channel channel = future.channel();
        return handleNewConnection(identifier, channel, this);
    } catch (InterruptedException e) {
        logger.error("Thread was interrupted during connect", e);
    } catch (ExecutionException e) {
        logger.error("ExecutionException in handleNewConnection for identifier " + identifier, e);
    }
    return null;
}

From source file:org.opendaylight.ovsdb.plugin.ConnectionService.java

License:Open Source License

private void ovsdbManager() {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*from  ww  w.ja  v a 2  s  .  c o m*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel channel) throws Exception {
                        logger.debug("New Passive channel created : " + channel.toString());
                        InetAddress address = channel.remoteAddress().getAddress();
                        int port = channel.remoteAddress().getPort();
                        String identifier = address.getHostAddress() + ":" + port;
                        channel.pipeline().addLast(new LoggingHandler(LogLevel.INFO),
                                new JsonRpcDecoder(10000000), new StringEncoder(CharsetUtil.UTF_8));

                        Node node = handleNewConnection(identifier, channel, ConnectionService.this);
                        logger.debug("Connected Node : " + node.toString());
                    }
                });
        b.option(ChannelOption.TCP_NODELAY, true);
        b.option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(65535, 65535, 65535));
        // Start the server.
        ChannelFuture f = b.bind(ovsdbListenPort).sync();
        serverListenChannel = f.channel();
        // Wait until the server socket is closed.
        serverListenChannel.closeFuture().sync();
    } catch (InterruptedException e) {
        logger.error("Thread interrupted", e);
    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:org.opendaylight.protocol.framework.AbstractDispatcher.java

License:Open Source License

/**
 * Creates server. Each server needs factories to pass their instances to client sessions.
 *
 * @param address address to which the server should be bound
 * @param channelClass The {@link Class} which is used to create {@link Channel} instances from.
 * @param initializer instance of PipelineInitializer used to initialize the channel pipeline
 *
 * @return ChannelFuture representing the binding process
 *//*w  w w. ja  v a  2s  .  c  o m*/
protected <CH extends Channel> ChannelFuture createServer(final SocketAddress address,
        final Class<? extends ServerChannel> channelClass,
        final ChannelPipelineInitializer<CH, S> initializer) {
    final ServerBootstrap b = new ServerBootstrap();
    b.childHandler(new ChannelInitializer<CH>() {

        @Override
        protected void initChannel(final CH ch) {
            initializer.initializeChannel(ch, new DefaultPromise<S>(executor));
        }
    });

    b.option(ChannelOption.SO_BACKLOG, 128);
    if (LocalServerChannel.class.equals(channelClass) == false) {
        // makes no sense for LocalServer and produces warning
        b.childOption(ChannelOption.SO_KEEPALIVE, true);
        b.childOption(ChannelOption.TCP_NODELAY, true);
    }
    b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    customizeBootstrap(b);

    if (b.group() == null) {
        b.group(bossGroup, workerGroup);
    }
    try {
        b.channel(channelClass);
    } catch (IllegalStateException e) {
        // FIXME: if this is ok, document why
        LOG.trace("Not overriding channelFactory on bootstrap {}", b, e);
    }

    // Bind and start to accept incoming connections.
    final ChannelFuture f = b.bind(address);
    LOG.debug("Initiated server {} at {}.", f, address);
    return f;
}

From source file:org.opendaylight.sxp.core.service.ConnectFacade.java

License:Open Source License

/**
 * Create new Connection to Peer//  w ww  . ja va2 s  .  co m
 *
 * @param node       SxpNode containing Security options
 * @param connection SxpConnection containing connection details
 * @param hf         HandlerFactory providing handling of communication
 * @return ChannelFuture callback
 */
public static ChannelFuture createClient(SxpNode node, SxpConnection connection, final HandlerFactory hf) {
    if (!Epoll.isAvailable()) {
        throw new UnsupportedOperationException(Epoll.unavailabilityCause().getCause());
    }
    Bootstrap bootstrap = new Bootstrap();
    if (connection.getPassword() != null && !connection.getPassword().isEmpty()) {
        bootstrap.option(EpollChannelOption.TCP_MD5SIG,
                Collections.singletonMap(connection.getDestination().getAddress(),
                        connection.getPassword().getBytes(StandardCharsets.US_ASCII)));
    }
    bootstrap.channel(EpollSocketChannel.class);
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, Configuration.NETTY_CONNECT_TIMEOUT_MILLIS);
    RecvByteBufAllocator recvByteBufAllocator = new FixedRecvByteBufAllocator(
            Configuration.getConstants().getMessageLengthMax());
    bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, recvByteBufAllocator);
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.localAddress(node.getSourceIp().getHostAddress(), 0);
    bootstrap.group(eventLoopGroup);
    bootstrap.handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(hf.getDecoders());
            ch.pipeline().addLast(hf.getEncoders());
        }
    });
    return bootstrap.connect(connection.getDestination());
}