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:io.jsync.net.impl.TCPSSLHelper.java

License:Open Source License

public void applyConnectionOptions(Bootstrap bootstrap) {
    bootstrap.option(ChannelOption.TCP_NODELAY, tcpNoDelay);
    if (tcpSendBufferSize != -1) {
        bootstrap.option(ChannelOption.SO_SNDBUF, tcpSendBufferSize);
    }//from w  w w . ja  va2 s  .c  om
    if (tcpReceiveBufferSize != -1) {
        bootstrap.option(ChannelOption.SO_RCVBUF, tcpReceiveBufferSize);
        bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(tcpReceiveBufferSize));
    }

    if (soLinger != -1) {
        bootstrap.option(ChannelOption.SO_LINGER, soLinger);
    }
    if (trafficClass != -1) {
        bootstrap.option(ChannelOption.IP_TOS, trafficClass);
    }
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout);
    bootstrap.option(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, tcpKeepAlive);
}

From source file:io.lettuce.core.AbstractRedisClient.java

License:Apache License

/**
 * Populate connection builder with necessary resources.
 *
 * @param socketAddressSupplier address supplier for initial connect and re-connect
 * @param connectionBuilder connection builder to configure the connection
 * @param redisURI URI of the Redis instance
 *//*from  ww w  .j  a  va  2s  .co  m*/
protected void connectionBuilder(Mono<SocketAddress> socketAddressSupplier, ConnectionBuilder connectionBuilder,
        RedisURI redisURI) {

    Bootstrap redisBootstrap = new Bootstrap();
    redisBootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
    redisBootstrap.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);
    redisBootstrap.option(ChannelOption.ALLOCATOR, BUF_ALLOCATOR);

    SocketOptions socketOptions = getOptions().getSocketOptions();

    redisBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,
            Math.toIntExact(socketOptions.getConnectTimeout().toMillis()));

    if (LettuceStrings.isEmpty(redisURI.getSocket())) {
        redisBootstrap.option(ChannelOption.SO_KEEPALIVE, socketOptions.isKeepAlive());
        redisBootstrap.option(ChannelOption.TCP_NODELAY, socketOptions.isTcpNoDelay());
    }

    connectionBuilder.timeout(redisURI.getTimeout());
    connectionBuilder.password(redisURI.getPassword());

    connectionBuilder.bootstrap(redisBootstrap);
    connectionBuilder.channelGroup(channels).connectionEvents(connectionEvents).timer(timer);
    connectionBuilder.socketAddressSupplier(socketAddressSupplier);
}

From source file:io.maelstorm.server.ServerInit.java

License:Open Source License

public void start(String configFile, RequestHandler handler) throws Exception {
    LOG.info("Starting.");
    AppendableCharSequenceAddon.configure();
    try {//from   ww  w.  j a v  a 2 s.c  o  m
        System.in.close(); // Release a FD we don't need.
    } catch (Exception e) {
        LOG.warn("Failed to close stdin", e);
    }
    Properties prop = getProperties(configFile);
    requestDistributor = handler;
    requestDistributor.setInitializer(this);
    String os = System.getProperty("os.name").toLowerCase(Locale.UK).trim();
    if (os.startsWith("linux")) {
        bossGroup = (null == bossGroup) ? new EpollEventLoopGroup(1) : bossGroup;
        workerGroup = (null == workerGroup) ? new EpollEventLoopGroup(NUM_WORKER_THREADS) : workerGroup;
    } else {
        bossGroup = (null == bossGroup) ? new NioEventLoopGroup(1) : bossGroup;
        workerGroup = (null == workerGroup) ? new NioEventLoopGroup(NUM_WORKER_THREADS) : workerGroup;
    }

    String[] servers = prop.getProperty("servers").split(",");
    for (String server : servers) {

        try {
            controller = new ServerBootstrap();
            controller.group(bossGroup, workerGroup);
            if (os.startsWith("linux")) {
                controller.channel(EpollServerSocketChannel.class);
                controller.option(EpollChannelOption.TCP_CORK, true);
            } else {
                controller.channel(NioServerSocketChannel.class);
            }
            controller.childHandler(new PipelineFactory(handler, getPipelineConfig(prop, server)));
            controller.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
            controller.option(ChannelOption.RCVBUF_ALLOCATOR, AdaptiveRecvByteBufAllocator.DEFAULT);
            controller.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,
                    getInt(prop, server, "connectTimeoutMillis"));
            controller.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 64 * 1024);
            controller.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 1 * 1024);
            controller.option(ChannelOption.SO_KEEPALIVE, getBoolean(prop, server, "SOKeepalive"));
            controller.option(ChannelOption.SO_REUSEADDR, true);
            controller.option(ChannelOption.TCP_NODELAY, true);
            controller.option(ChannelOption.SO_LINGER, 0);
            controller.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
            controller.childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 64 * 1024);
            controller.childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 10);
            controller.childOption(ChannelOption.SO_KEEPALIVE, true);
            controller.childOption(ChannelOption.SO_REUSEADDR, true);
            controller.childOption(ChannelOption.TCP_NODELAY, true);
            controller.childOption(ChannelOption.SO_LINGER, 0);
            controller.childOption(ChannelOption.SO_RCVBUF, 6291456);

            final InetSocketAddress addr = new InetSocketAddress(getInt(prop, server, "port"));
            ChannelFuture future = controller.bind(addr).sync();
            if (future.isSuccess())
                LOG.info("Server Ready to serve on " + addr);
            else
                throw new Exception("Address already in use");
        } catch (Throwable t) {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
            throw new RuntimeException("Initialization failed", t);
        }
    }
}

From source file:io.moquette.server.netty.NettyAcceptor.java

License:Open Source License

private void initFactory(String host, int port, final PipelineInitializer pipeliner) {
    ServerBootstrap b = new ServerBootstrap();
    b.group(m_bossGroup, m_workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override/*  w  ww.  ja  v  a2s  . c om*/
                public void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    try {
                        pipeliner.init(pipeline);
                    } catch (Throwable th) {
                        LOG.error("Severe error during pipeline creation", th);
                        throw th;
                    }
                }
            }).option(ChannelOption.SO_BACKLOG, 128).option(ChannelOption.SO_REUSEADDR, true)
            .option(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true);
    try {
        // Bind and start to accept incoming connections.
        ChannelFuture f = b.bind(host, port);
        LOG.info("Server binded host: {}, port: {}", host, port);
        f.sync();
    } catch (InterruptedException ex) {
        LOG.error(null, ex);
    }
}

From source file:io.mycat.netty.NettyServer.java

License:Apache License

private ServerBootstrap configServer() {
    bossGroup = new NioEventLoopGroup(args.bossThreads, new DefaultThreadFactory("NettyBossGroup", true));
    workerGroup = new NioEventLoopGroup(args.workerThreads, new DefaultThreadFactory("NettyWorkerGroup", true));
    userExecutor = createUserThreadExecutor();

    final ProtocolHandler handshakeHandler = newHandshakeHandler(userExecutor);
    final ProtocolHandler protocolHandler = newProtocolHandler(userExecutor);

    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childOption(ChannelOption.SO_REUSEADDR, true).childOption(ChannelOption.SO_KEEPALIVE, true)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.TCP_NODELAY, true);

    if (args.socketTimeoutMills > 0) {
        b.childOption(ChannelOption.SO_TIMEOUT, args.socketTimeoutMills);
    }/*from   w  w  w . j av a2  s  . c o  m*/

    if (args.recvBuff > 0) {
        b.childOption(ChannelOption.SO_RCVBUF, args.recvBuff);
    }

    if (args.sendBuff > 0) {
        b.childOption(ChannelOption.SO_SNDBUF, args.sendBuff);
    }

    b.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(createProtocolDecoder(), /* createProtocolEncoder(), */ handshakeHandler,
                    protocolHandler);
        }
    });

    return b;
}

From source file:io.nebo.container.NettyEmbeddedServletContainer.java

License:Apache License

private void groups(ServerBootstrap b) {
    if (StandardSystemProperty.OS_NAME.value().equals("Linux")) {
        bossGroup = new EpollEventLoopGroup(1);
        workerGroup = new EpollEventLoopGroup();
        b.channel(EpollServerSocketChannel.class).group(bossGroup, workerGroup)
                .option(EpollChannelOption.TCP_CORK, true);
    } else {/*  ww w . j av  a2  s .c o m*/
        bossGroup = new NioEventLoopGroup(1);
        workerGroup = new NioEventLoopGroup();
        b.channel(NioServerSocketChannel.class).group(bossGroup, workerGroup);
    }
    b.option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_REUSEADDR, true)
            .option(ChannelOption.SO_BACKLOG, 100);
    logger.info("Bootstrap configuration: " + b.toString());
}

From source file:io.netlibs.bgp.netty.service.BGPv4Client.java

License:Apache License

public ChannelFuture startClient(final PeerConfiguration peerConfiguration) {

    final Bootstrap b = new Bootstrap();

    b.group(workerGroup);// ww w.  ja  v a2s. c  o  m
    b.channel(NioSocketChannel.class);

    b.option(ChannelOption.TCP_NODELAY, true);
    b.option(ChannelOption.SO_KEEPALIVE, true);

    b.handler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(final SocketChannel ch) throws Exception {
            ch.pipeline().addLast(BGPv4Reframer.HANDLER_NAME, new BGPv4Reframer());
            ch.pipeline().addLast(BGPv4Codec.HANDLER_NAME, new BGPv4Codec(BGPv4PacketDecoder.getInstance()));
            ch.pipeline().addLast(InboundOpenCapabilitiesProcessor.HANDLER_NAME,
                    new InboundOpenCapabilitiesProcessor());
            ch.pipeline().addLast(ValidateServerIdentifier.HANDLER_NAME, new ValidateServerIdentifier());
            ch.pipeline().addLast(BGPv4ClientEndpoint.HANDLER_NAME,
                    new BGPv4ClientEndpoint(BGPv4Client.this.registry));
        }

    });

    // Start the client.
    return b.connect(peerConfiguration.getClientConfig().getRemoteAddress());

}

From source file:io.netlibs.bgp.netty.service.BGPv4Server.java

License:Apache License

public void startServer() {

    ServerBootstrap bootstrap = new ServerBootstrap();

    bootstrap.group(new NioEventLoopGroup(), new NioEventLoopGroup());

    bootstrap.channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
        @Override//w  ww .j a v  a  2  s.c  o  m
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast(BGPv4Reframer.HANDLER_NAME, BGPv4Server.this.reframer);
            pipeline.addLast(BGPv4Codec.HANDLER_NAME, BGPv4Server.this.codec);
            pipeline.addLast(InboundOpenCapabilitiesProcessor.HANDLER_NAME,
                    BGPv4Server.this.inboundOpenCapProcessor);
            pipeline.addLast(ValidateServerIdentifier.HANDLER_NAME, BGPv4Server.this.validateServer);
            pipeline.addLast(BGPv4ServerEndpoint.HANDLER_NAME, BGPv4Server.this.serverEndpoint);
        }
    });

    bootstrap.option(ChannelOption.SO_BACKLOG, 128);

    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.childOption(ChannelOption.TCP_NODELAY, true);

    log.info("Starting local server");

    this.serverChannel = bootstrap.bind(applicationConfiguration.getServerPort()).syncUninterruptibly()
            .channel();

}

From source file:io.pravega.client.netty.impl.ConnectionFactoryImpl.java

License:Open Source License

@Override
public CompletableFuture<ClientConnection> establishConnection(PravegaNodeUri location, ReplyProcessor rp) {
    Preconditions.checkNotNull(location);
    Exceptions.checkNotClosed(closed.get(), this);
    final SslContext sslCtx;
    if (ssl) {//  w  w w.j a  v  a2  s .  c  om
        try {
            sslCtx = SslContextBuilder.forClient().trustManager(FingerprintTrustManagerFactory
                    .getInstance(FingerprintTrustManagerFactory.getDefaultAlgorithm())).build();
        } catch (SSLException | NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    } else {
        sslCtx = null;
    }
    AppendBatchSizeTracker batchSizeTracker = new AppendBatchSizeTrackerImpl();
    ClientConnectionInboundHandler handler = new ClientConnectionInboundHandler(location.getEndpoint(), rp,
            batchSizeTracker);
    Bootstrap b = new Bootstrap();
    b.group(group).channel(nio ? NioSocketChannel.class : EpollSocketChannel.class)
            .option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    if (sslCtx != null) {
                        p.addLast(sslCtx.newHandler(ch.alloc(), location.getEndpoint(), location.getPort()));
                    }
                    // p.addLast(new LoggingHandler(LogLevel.INFO));
                    p.addLast(new ExceptionLoggingHandler(location.getEndpoint()),
                            new CommandEncoder(batchSizeTracker),
                            new LengthFieldBasedFrameDecoder(WireCommands.MAX_WIRECOMMAND_SIZE, 4, 4),
                            new CommandDecoder(), handler);
                }
            });

    // Start the client.
    CompletableFuture<ClientConnection> result = new CompletableFuture<>();
    try {
        b.connect(location.getEndpoint(), location.getPort()).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) {
                if (future.isSuccess()) {
                    result.complete(handler);
                } else {
                    result.completeExceptionally(future.cause());
                }
            }
        });
    } catch (Exception e) {
        result.completeExceptionally(e);
    }
    return result;
}

From source file:io.reactivesocket.netty.tcp.client.ClientTcpDuplexConnection.java

License:Apache License

public static Publisher<ClientTcpDuplexConnection> create(SocketAddress address,
        EventLoopGroup eventLoopGroup) {
    return s -> {
        CopyOnWriteArrayList<Observer<Frame>> subjects = new CopyOnWriteArrayList<>();
        ReactiveSocketClientHandler clientHandler = new ReactiveSocketClientHandler(subjects);
        Bootstrap bootstrap = new Bootstrap();
        ChannelFuture connect = bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_REUSEADDR, true)
                .option(ChannelOption.AUTO_READ, true).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override//from w w w.j  av a 2 s.c o m
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE >> 1, 0,
                                BitUtil.SIZE_OF_INT, -1 * BitUtil.SIZE_OF_INT, 0), clientHandler);
                    }
                }).connect(address);

        connect.addListener(connectFuture -> {
            if (connectFuture.isSuccess()) {
                Channel ch = connect.channel();
                s.onNext(new ClientTcpDuplexConnection(ch, subjects));
                s.onComplete();
            } else {
                s.onError(connectFuture.cause());
            }
        });
    };
}