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:com.dinstone.jrpc.transport.netty5.NettyConnector.java

License:Apache License

public NettyConnector(InetSocketAddress isa, final TransportConfig transportConfig) {
    workerGroup = new NioEventLoopGroup(1, new DefaultExecutorServiceFactory("N5C-Work"));
    clientBoot = new Bootstrap().group(workerGroup).channel(NioSocketChannel.class);
    clientBoot.option(ChannelOption.TCP_NODELAY, true);
    clientBoot.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, transportConfig.getConnectTimeout());
    clientBoot.option(ChannelOption.SO_RCVBUF, 8 * 1024).option(ChannelOption.SO_SNDBUF, 8 * 1024);
    clientBoot.handler(new ChannelInitializer<SocketChannel>() {

        @Override/* w w w  .  j av  a 2 s .  c om*/
        public void initChannel(SocketChannel ch) throws Exception {
            TransportProtocolDecoder decoder = new TransportProtocolDecoder();
            decoder.setMaxObjectSize(transportConfig.getMaxSize());
            TransportProtocolEncoder encoder = new TransportProtocolEncoder();
            encoder.setMaxObjectSize(transportConfig.getMaxSize());
            ch.pipeline().addLast("TransportProtocolDecoder", decoder);
            ch.pipeline().addLast("TransportProtocolEncoder", encoder);

            int intervalSeconds = transportConfig.getHeartbeatIntervalSeconds();
            ch.pipeline().addLast("IdleStateHandler", new IdleStateHandler(0, intervalSeconds, 0));
            ch.pipeline().addLast("NettyClientHandler", new NettyClientHandler());
        }
    });

    clientBoot.remoteAddress(isa);
}

From source file:com.diwayou.hybrid.remoting.netty.NettyRemotingClient.java

License:Apache License

@Override
public void start() {
    this.defaultEventExecutorGroup = new DefaultEventExecutorGroup(//
            nettyClientConfig.getClientWorkerThreads(), //
            new ThreadFactory() {

                private AtomicInteger threadIndex = new AtomicInteger(0);

                @Override//w  w  w  .  j  a v a  2 s . com
                public Thread newThread(Runnable r) {
                    return new Thread(r, "NettyClientWorkerThread_" + this.threadIndex.incrementAndGet());
                }
            });

    Bootstrap handler = this.bootstrap.group(this.eventLoopGroupWorker).channel(NioSocketChannel.class)//
            //
            .option(ChannelOption.TCP_NODELAY, true)
            //
            .option(ChannelOption.SO_KEEPALIVE, false)
            //
            .option(ChannelOption.SO_SNDBUF, nettyClientConfig.getClientSocketSndBufSize())
            //
            .option(ChannelOption.SO_RCVBUF, nettyClientConfig.getClientSocketRcvBufSize())
            //
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(//
                            defaultEventExecutorGroup, //
                            new NettyEncoder(), //
                            new NettyDecoder(), //
                            new IdleStateHandler(0, 0, nettyClientConfig.getClientChannelMaxIdleTimeSeconds()), //
                            new NettyConnetManageHandler(), //
                            new NettyClientHandler());
                }
            });

    // ?1??
    this.timer.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {
            try {
                NettyRemotingClient.this.scanResponseTable();
            } catch (Exception e) {
                log.error("scanResponseTable exception", e);
            }
        }
    }, 1000 * 3, 1000);

    if (this.channelEventListener != null) {
        this.nettyEventExecuter.start();
    }
}

From source file:com.diwayou.hybrid.remoting.netty.NettyRemotingServer.java

License:Apache License

@Override
public void start() {
    this.defaultEventExecutorGroup = new DefaultEventExecutorGroup(//
            nettyServerConfig.getServerWorkerThreads(), //
            new ThreadFactory() {

                private AtomicInteger threadIndex = new AtomicInteger(0);

                @Override// w  w w  . j a v a2 s .c om
                public Thread newThread(Runnable r) {
                    return new Thread(r, "NettyServerWorkerThread_" + this.threadIndex.incrementAndGet());
                }
            });

    ServerBootstrap childHandler = //
            this.serverBootstrap.group(this.eventLoopGroupBoss, this.eventLoopGroupWorker)
                    .channel(NioServerSocketChannel.class)
                    //
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    //
                    .option(ChannelOption.SO_REUSEADDR, true)
                    //
                    .option(ChannelOption.SO_KEEPALIVE, false)
                    //
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    //
                    .option(ChannelOption.SO_SNDBUF, nettyServerConfig.getServerSocketSndBufSize())
                    //
                    .option(ChannelOption.SO_RCVBUF, nettyServerConfig.getServerSocketRcvBufSize())
                    //
                    .localAddress(new InetSocketAddress(this.nettyServerConfig.getListenPort()))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(
                                    //
                                    defaultEventExecutorGroup, //
                                    new NettyEncoder(), //
                                    new NettyDecoder(), //
                                    new IdleStateHandler(0, 0,
                                            nettyServerConfig.getServerChannelMaxIdleTimeSeconds()), //
                                    new NettyConnetManageHandler(), //
                                    new NettyServerHandler());
                        }
                    });

    if (nettyServerConfig.isServerPooledByteBufAllocatorEnable()) {
        // ????
        childHandler.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    }

    try {
        ChannelFuture sync = this.serverBootstrap.bind().sync();
        InetSocketAddress addr = (InetSocketAddress) sync.channel().localAddress();
        this.port = addr.getPort();
    } catch (InterruptedException e1) {
        throw new RuntimeException("this.serverBootstrap.bind().sync() InterruptedException", e1);
    }

    if (this.channelEventListener != null) {
        this.nettyEventExecuter.start();
    }

    // ?1??
    this.timer.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {
            try {
                NettyRemotingServer.this.scanResponseTable();
            } catch (Exception e) {
                log.error("scanResponseTable exception", e);
            }
        }
    }, 1000 * 3, 1000);
}

From source file:com.doctor.netty5.ebook.netty_the_definitive_guide.Chapter4ForTimerClient.java

License:Apache License

public void connect(String host, int port) throws InterruptedException {
    EventLoopGroup group = new NioEventLoopGroup();
    try {/*from  ww  w  .  j  av  a2 s.c om*/
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new LineBasedFrameDecoder(2014));
                        ch.pipeline().addLast(new StringDecoder());
                        ch.pipeline().addLast(new TimeClientHander());

                    }
                });

        ChannelFuture f = b.connect(host, port).sync();
        f.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }

}

From source file:com.doctor.netty5.ebook.netty_the_definitive_guide.TimerClient.java

License:Apache License

public void connect(String host, int port) throws InterruptedException {
    EventLoopGroup group = new NioEventLoopGroup();
    try {//from   www.ja  va2  s .com
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new TimeClientHander());

                    }
                });

        ChannelFuture f = b.connect(host, port).sync();
        f.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }

}

From source file:com.ebay.jetstream.http.netty.client.HttpClient.java

License:MIT License

private void createChannelPipeline() {

    if (isPipelineCreated())
        return;/*from   ww w .j a  va  2 s  .co  m*/

    m_workerGroup = new NioEventLoopGroup(getConfig().getNumWorkers(),
            new NameableThreadFactory("Jetstream-HttpClientWorker"));
    m_bootstrap = new Bootstrap();
    m_bootstrap.group(m_workerGroup).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
            .option(ChannelOption.SO_KEEPALIVE, false)
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, getConfig().getConnectionTimeoutInSecs())
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast("timeout",
                            new IdleStateHandler(0, getConfig().getIdleTimeoutInSecs(), 0));
                    ch.pipeline().addLast("decoder", new HttpResponseDecoder());
                    ch.pipeline().addLast("decompressor", new HttpContentDecompressor());
                    ch.pipeline().addLast("encoder", new HttpRequestEncoder());
                    ch.pipeline().addLast("aggregator",
                            new HttpObjectAggregator(m_config.getMaxContentLength()));
                    ch.pipeline().addLast(m_httpRequestHandler);
                }
            });

    if (getConfig().getRvcBufSz() > 0) {
        m_bootstrap.option(ChannelOption.SO_RCVBUF, (int) getConfig().getRvcBufSz());
    }

    if (getConfig().getSendBufSz() > 0) {
        m_bootstrap.option(ChannelOption.SO_SNDBUF, (int) getConfig().getSendBufSz());
    }
    createdPipeline();

}

From source file:com.ebay.jetstream.http.netty.server.Acceptor.java

License:MIT License

/**
 * @param rxSessionHandler//from w ww .  j a v  a  2 s. co  m
 * @throws Exception
 */
public void bind(final HttpRequestHandler httpReqHandler, final HttpServerStatisticsHandler statisticsHandler)
        throws Exception {
    m_bossGroup = new NioEventLoopGroup(1, new NameableThreadFactory("NettyHttpServerAcceptor"));
    m_workerGroup = new NioEventLoopGroup(m_numIoProcessors,
            new NameableThreadFactory("NettyHttpServerWorker"));

    try {
        m_serverbootstrap = new ServerBootstrap();
        m_serverbootstrap.group(m_bossGroup, m_workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast("timeout", new IdleStateHandler((int) m_readIdleTimeout, 0, 0));
                        ch.pipeline().addLast("stats", statisticsHandler);
                        ch.pipeline().addLast("decoder", new HttpRequestDecoder());
                        ch.pipeline().addLast("encoder", new HttpResponseEncoder());
                        ch.pipeline().addLast("decompressor", new HttpContentDecompressor());
                        ch.pipeline().addLast("deflater", new HttpContentCompressor(1));
                        ch.pipeline().addLast("aggregator", new HttpObjectAggregator(m_maxContentLength));
                        if (m_maxKeepAliveRequests > 0 || m_maxKeepAliveTimeout > 0) {
                            ch.pipeline().addLast("keepAliveHandler",
                                    new KeepAliveHandler(m_maxKeepAliveRequests, m_maxKeepAliveTimeout));
                        }
                        ch.pipeline().addLast("handler", httpReqHandler);

                    }

                }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.TCP_NODELAY, true)
                .childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
                .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .childOption(ChannelOption.SO_KEEPALIVE, false);

        if (m_config.getRvcBufSz() > 0) {
            m_serverbootstrap.childOption(ChannelOption.SO_RCVBUF, (int) m_config.getRvcBufSz());
        }

        if (m_config.getSendBufSz() > 0) {
            m_serverbootstrap.childOption(ChannelOption.SO_SNDBUF, (int) m_config.getSendBufSz());
        }

    } catch (Exception t) {
        throw t;
    }

    m_acceptorSocket = new InetSocketAddress(m_ipAddress, m_tcpPort);
    m_serverbootstrap.bind(m_acceptorSocket).sync();

    if (!m_ipAddress.isLoopbackAddress() && !m_ipAddress.isAnyLocalAddress()) {
        // Add lookback if not bind
        m_localAcceptorSocket = new InetSocketAddress("127.0.0.1", m_tcpPort);
        m_serverbootstrap.bind(m_localAcceptorSocket).sync();
    }
}

From source file:com.ebay.jetstream.messaging.transport.netty.eventconsumer.Acceptor.java

License:MIT License

/**
 * @param rxSessionHandler//  w  w w.  j a  v a2 s . c  om
 * @throws Exception
 */
public void bind(EventProducerSessionHandler rxSessionHandler) throws Exception {

    m_rxSessionHandler = rxSessionHandler;
    m_bossGroup = new NioEventLoopGroup(1,
            new NameableThreadFactory("NettyAcceptor-" + m_tc.getTransportName()));
    m_workerGroup = new NioEventLoopGroup(m_numIoProcessors,
            new NameableThreadFactory("NettyReceiver-" + m_tc.getTransportName()));

    try {
        m_serverbootstrap = new ServerBootstrap();
        m_serverbootstrap.group(m_bossGroup, m_workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {

                        ch.pipeline().addFirst("msghandler", m_rxSessionHandler);

                        StreamMessageDecoder decoder = new StreamMessageDecoder(
                                ClassResolvers.weakCachingConcurrentResolver(null));
                        ch.pipeline().addBefore("msghandler", "msgdecoder", decoder);
                        ch.pipeline().addBefore("msgdecoder", "kryoEcnoder", new KryoObjectEncoder());
                        ch.pipeline().addBefore("kryoEcnoder", "msgencoder", new NettyObjectEncoder());

                        if (m_enableCompression) {

                            ch.pipeline().addBefore("msgencoder", "decompressor",
                                    new MessageDecompressionHandler(false, 250000));

                            ch.pipeline().addBefore("decompressor", "idleTimeoutHandler",
                                    new IdleStateHandler((int) m_readIdleTimeout, 0, 0));
                        } else
                            ch.pipeline().addBefore("msgencoder", "idleTimeoutHandler",
                                    new IdleStateHandler((int) m_readIdleTimeout, 0, 0));

                    }
                }).option(ChannelOption.SO_BACKLOG, 128)
                .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .childOption(ChannelOption.TCP_NODELAY, true)
                .childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
                .childOption(ChannelOption.SO_KEEPALIVE, isTcpKeepAlive());

        if (m_tc.getReceivebuffersize() > 0) {
            m_serverbootstrap.childOption(ChannelOption.SO_RCVBUF, m_tc.getReceivebuffersize());
        }

        if (m_tc.getSendbuffersize() > 0) {
            m_serverbootstrap.childOption(ChannelOption.SO_SNDBUF, m_tc.getSendbuffersize());
        }

    } catch (Exception t) {
        throw t;
    }

    // we are given a port from DNS. We will check if it is taken. If it is
    // we will increment the port # by 10 and keep trying 10 times.
    // adding this feature so that we can operate the cluster on a single
    // node. Very useful for debugging and also for demos.

    int retryCount = 20;
    int port = m_tcpPort;

    while (retryCount-- > 0) {
        if (isPortAvailable(port))
            break;
        port += 1;

    }

    if (retryCount == 0)
        return; // we did not find a port to bind

    m_tcpPort = port;

    LOGGER.info("Acceptor bound to port" + m_tcpPort);

}

From source file:com.ebay.jetstream.messaging.transport.netty.eventproducer.EventProducer.java

License:MIT License

/**
 * //from  w  w w.j  a va 2s  .  c o  m
 */
private void createChannelPipeline() {

    m_group = new NioEventLoopGroup(m_transportConfig.getNumConnectorIoProcessors(),
            new NameableThreadFactory("NettySender-" + m_transportConfig.getTransportName()));
    m_bootstrap = new Bootstrap();
    m_bootstrap.group(m_group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
            .option(ChannelOption.SO_KEEPALIVE, m_transportConfig.getTcpKeepAlive())
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, m_transportConfig.getConnectionTimeoutInSecs() * 1000)
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {

                    StreamMessageDecoder decoder = new StreamMessageDecoder(ClassResolvers.cacheDisabled(null));

                    if (m_autoFlushHandler != null) {
                        ch.pipeline().addLast(new EventConsumerStatisticsHandler(),
                                new MessageCompressionHandler(),
                                new IdleStateHandler(m_transportConfig.getIdleTimeoutInSecs(), 0, 0),
                                m_autoFlushHandler, decoder, new NettyObjectEncoder(), new KryoObjectEncoder(),
                                m_ecSessionHandler);
                    } else {
                        ch.pipeline().addLast(new EventConsumerStatisticsHandler(),
                                new MessageCompressionHandler(), decoder, new NettyObjectEncoder(),
                                new KryoObjectEncoder(), m_ecSessionHandler);
                    }
                }
            });

    if (m_transportConfig.getReceivebuffersize() > 0) {
        m_bootstrap.option(ChannelOption.SO_RCVBUF, m_transportConfig.getReceivebuffersize());
    }

    if (m_transportConfig.getSendbuffersize() > 0) {
        m_bootstrap.option(ChannelOption.SO_SNDBUF, m_transportConfig.getSendbuffersize());
    }
}

From source file:com.eucalyptus.ws.WebServices.java

License:Open Source License

private static io.netty.bootstrap.Bootstrap clientBootstrap(final EventLoopGroup group) {
    return new io.netty.bootstrap.Bootstrap().group(group).channel(NioSocketChannel.class)
            .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.SO_REUSEADDR, true).option(ChannelOption.CONNECT_TIMEOUT_MILLIS,
                    StackConfiguration.CLIENT_INTERNAL_CONNECT_TIMEOUT_MILLIS);
}