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.wolfbe.configcenter.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/*from   w ww.  j  av  a2 s.c om*/
                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.CONNECT_TIMEOUT_MILLIS, nettyClientConfig.getConnectTimeoutMillis())
            //
            .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());
                }
            });

    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.wolfbe.configcenter.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  .co  m*/
                public Thread newThread(Runnable r) {
                    return new Thread(r, "NettyServerCodecThread_" + this.threadIndex.incrementAndGet());
                }
            });

    ServerBootstrap childHandler = //
            this.serverBootstrap.group(this.eventLoopGroupBoss, this.eventLoopGroupSelector)
                    .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();
    }

    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.xing.netty.client.DiscardClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/*  w  w w . j ava  2  s  .c om*/
        sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
    } else {
        sslCtx = null;
    }

    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<Channel>() {

                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        // if (sslCtx != null) {
                        // p.addLast(sslCtx.newHandler(ch.alloc(), HOST,
                        // PORT));
                        // }
                        // p.addLast(new DiscardClientHandler());
                        ByteBuf delimiter = Unpooled.copiedBuffer("$_".getBytes());
                        p.addLast(new DelimiterBasedFrameDecoder(1024, delimiter));
                        // p.addLast(new LineBasedFrameDecoder(1024));
                        p.addLast(new StringDecoder());
                        p.addLast(new TimeClientHandler());
                    }
                });
        // Make the connection attempt.
        ChannelFuture f = b.connect(HOST, PORT).sync();

        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
    } catch (Exception e) {
        System.out.println(e);
    } finally {
        group.shutdownGracefully();
    }
}

From source file:com.xxx.util.io.client.netty.EchoClient.java

License:Apache License

public void doOpen() throws Exception {
    // Configure the client.
    try {// w ww  .ja v  a 2 s  .  c om
        bootstrap = new Bootstrap();
        bootstrap.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        //p.addLast(new LoggingHandler(LogLevel.INFO));
                        p.addLast(new EchoClientHandler(headSize, isLongConnect));
                    }
                });

    } finally {
        // Shut down the event loop to terminate all threads.
        //group.shutdownGracefully();
    }
}

From source file:com.xyz.rpc.netty4.server.Netty4Server.java

License:Apache License

public void start(int listenPort, final ExecutorService ignore) throws Exception {
    if (!startFlag.compareAndSet(false, true)) {
        return;/*from  ww  w  .  jav  a  2 s.  c o m*/
    }
    bossGroup = new NioEventLoopGroup();
    ioGroup = new NioEventLoopGroup();
    businessGroup = new DefaultEventExecutorGroup(businessThreads);

    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, ioGroup).channel(NioServerSocketChannel.class)
            .childOption(ChannelOption.TCP_NODELAY,
                    Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.nodelay", "true")))
            .childOption(ChannelOption.SO_REUSEADDR,
                    Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.reuseaddress", "true")))
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast("decoder", new Netty4ProtocolDecoder());
                    ch.pipeline().addLast("encoder", new Netty4ProtocolEncoder());
                    ch.pipeline().addLast(businessGroup, "handler", new Netty4ServerHandler());
                }
            });
    b.bind(new InetSocketAddress("127.0.0.1", listenPort)).sync();
    LOGGER.warn("Server started,listen at: " + listenPort + ", businessThreads is " + businessThreads);
}

From source file:com.yahoo.pulsar.broker.service.BrokerService.java

License:Apache License

public void start() throws Exception {
    this.producerNameGenerator = new DistributedIdGenerator(pulsar.getZkClient(), producerNameGeneratorPath,
            pulsar.getConfiguration().getClusterName());

    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    bootstrap.group(acceptorGroup, workerGroup);
    bootstrap.childOption(ChannelOption.TCP_NODELAY, true);
    bootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR,
            new AdaptiveRecvByteBufAllocator(1024, 16 * 1024, 1 * 1024 * 1024));

    if (workerGroup instanceof EpollEventLoopGroup) {
        bootstrap.channel(EpollServerSocketChannel.class);
        bootstrap.childOption(EpollChannelOption.EPOLL_MODE, EpollMode.LEVEL_TRIGGERED);
    } else {/*from  www .j  ava  2s . c  o  m*/
        bootstrap.channel(NioServerSocketChannel.class);
    }

    ServiceConfiguration serviceConfig = pulsar.getConfiguration();

    bootstrap.childHandler(new PulsarChannelInitializer(this, serviceConfig, false));
    // Bind and start to accept incoming connections.
    bootstrap.bind(new InetSocketAddress(pulsar.getBindAddress(), port)).sync();
    log.info("Started Pulsar Broker service on port {}", port);

    if (serviceConfig.isTlsEnabled()) {
        ServerBootstrap tlsBootstrap = bootstrap.clone();
        tlsBootstrap.childHandler(new PulsarChannelInitializer(this, serviceConfig, true));
        tlsBootstrap.bind(new InetSocketAddress(pulsar.getBindAddress(), tlsPort)).sync();
        log.info("Started Pulsar Broker TLS service on port {}", tlsPort);
    }

    // start other housekeeping functions
    this.startStatsUpdater();
    this.startInactivityMonitor();
    this.startMessageExpiryMonitor();
    this.startBacklogQuotaChecker();
}

From source file:com.yahoo.pulsar.broker.service.ServerCnx.java

License:Apache License

private final void disableTcpNoDelayIfNeeded(String topic, String producerName) {
    if (producerName != null && producerName.startsWith(replicatorPrefix)) {
        // Re-enable nagle algorithm on connections used for replication purposes
        try {/*from  w  ww  .  java2 s  .c om*/
            if (ctx.channel().config().getOption(ChannelOption.TCP_NODELAY).booleanValue() == true) {
                ctx.channel().config().setOption(ChannelOption.TCP_NODELAY, false);
            }
        } catch (Throwable t) {
            log.warn("[{}] [{}] Failed to remove TCP no-delay property on client cnx {}", topic, producerName,
                    ctx.channel());
        }
    }
}

From source file:com.yahoo.pulsar.client.impl.ConnectionPool.java

License:Apache License

public ConnectionPool(final PulsarClientImpl client, EventLoopGroup eventLoopGroup) {
    this.eventLoopGroup = eventLoopGroup;
    this.maxConnectionsPerHosts = client.getConfiguration().getConnectionsPerBroker();

    pool = new ConcurrentHashMap<>();
    bootstrap = new Bootstrap();
    bootstrap.group(eventLoopGroup);// www . j a v a 2 s .c o m
    if (SystemUtils.IS_OS_LINUX && eventLoopGroup instanceof EpollEventLoopGroup) {
        bootstrap.channel(EpollSocketChannel.class);
    } else {
        bootstrap.channel(NioSocketChannel.class);
    }

    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);
    bootstrap.option(ChannelOption.TCP_NODELAY, client.getConfiguration().isUseTcpNoDelay());
    bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    bootstrap.handler(new ChannelInitializer<SocketChannel>() {
        public void initChannel(SocketChannel ch) throws Exception {
            ClientConfiguration clientConfig = client.getConfiguration();
            if (clientConfig.isUseTls()) {
                SslContextBuilder builder = SslContextBuilder.forClient();
                if (clientConfig.isTlsAllowInsecureConnection()) {
                    builder.trustManager(InsecureTrustManagerFactory.INSTANCE);
                } else {
                    if (clientConfig.getTlsTrustCertsFilePath().isEmpty()) {
                        // Use system default
                        builder.trustManager((File) null);
                    } else {
                        File trustCertCollection = new File(clientConfig.getTlsTrustCertsFilePath());
                        builder.trustManager(trustCertCollection);
                    }
                }

                // Set client certificate if available
                AuthenticationDataProvider authData = clientConfig.getAuthentication().getAuthData();
                if (authData.hasDataForTls()) {
                    builder.keyManager(authData.getTlsPrivateKey(),
                            (X509Certificate[]) authData.getTlsCertificates());
                }

                SslContext sslCtx = builder.build();
                ch.pipeline().addLast(TLS_HANDLER, sslCtx.newHandler(ch.alloc()));
            }
            ch.pipeline().addLast("frameDecoder",
                    new PulsarLengthFieldFrameDecoder(MaxMessageSize, 0, 4, 0, 4));
            ch.pipeline().addLast("handler", new ClientCnx(client));
        }
    });
}

From source file:com.yahoo.pulsar.discovery.service.DiscoveryService.java

License:Apache License

/**
 * starts server to handle discovery-request from client-channel
 * /*from   ww  w .j a  v a 2s .  co  m*/
 * @throws Exception
 */
public void startServer() throws Exception {

    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    bootstrap.group(acceptorGroup, workerGroup);
    bootstrap.childOption(ChannelOption.TCP_NODELAY, true);
    bootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR,
            new AdaptiveRecvByteBufAllocator(1024, 16 * 1024, 1 * 1024 * 1024));

    if (workerGroup instanceof EpollEventLoopGroup) {
        bootstrap.channel(EpollServerSocketChannel.class);
        bootstrap.childOption(EpollChannelOption.EPOLL_MODE, EpollMode.LEVEL_TRIGGERED);
    } else {
        bootstrap.channel(NioServerSocketChannel.class);
    }

    bootstrap.childHandler(new ServiceChannelInitializer(this, config, false));
    // Bind and start to accept incoming connections.
    bootstrap.bind(config.getServicePort()).sync();
    LOG.info("Started Pulsar Broker service on port {}", config.getWebServicePort());

    if (config.isTlsEnabled()) {
        ServerBootstrap tlsBootstrap = bootstrap.clone();
        tlsBootstrap.childHandler(new ServiceChannelInitializer(this, config, true));
        tlsBootstrap.bind(config.getServicePortTls()).sync();
        LOG.info("Started Pulsar Broker TLS service on port {}", config.getWebServicePortTls());
    }
}

From source file:com.zaradai.distributor.messaging.netty.NettyClient.java

License:Apache License

private void configure(Bootstrap b) {
    b.option(ChannelOption.TCP_NODELAY, config.getTcpNoDelay());
    b.option(ChannelOption.SO_KEEPALIVE, config.getKeepAlive());
    b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.getConnectionTimeout());
}