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.kixeye.kixmpp.p2p.node.NodeServer.java

License:Apache License

public void initialize(final String host, final int port, final EventLoopGroup bossGroup,
        final EventLoopGroup workerGroup, final MessageRegistry messageRegistry,
        final ChannelInboundHandlerAdapter channelListener) {
    ServerBootstrap boot = new ServerBootstrap();
    boot.group(bossGroup, workerGroup);//www . j ava  2 s .c  om
    boot.channel(NioServerSocketChannel.class);
    boot.option(ChannelOption.SO_BACKLOG, 32);
    boot.childOption(ChannelOption.SO_KEEPALIVE, true);
    boot.childOption(ChannelOption.TCP_NODELAY, true);
    boot.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();

            //p.addLast(new LoggingHandler());

            // encoders
            p.addLast(new LengthFieldPrepender(4));
            p.addLast(new ProtostuffEncoder(messageRegistry));

            // decoders
            p.addLast(new LengthFieldBasedFrameDecoder(0x100000, 0, 4, 0, 4));
            p.addLast(new ProtostuffDecoder(messageRegistry));
            p.addLast(channelListener);
        }
    });

    // start accepting connection
    try {
        logger.info("Starting NodeServer on [{}]...", port);

        if (host == null) {
            acceptChannel = boot.bind(port).sync().channel();
        } else {
            acceptChannel = boot.bind(host, port).sync().channel();
        }

        logger.info("NodeServer listening on [{}]...", port);
    } catch (InterruptedException e) {
        logger.error("Binding to port {} failed", port, e);
    }

}

From source file:com.lambdaworks.redis.AbstractRedisClient.java

License:Apache License

/**
 * Populate connection builder with necessary resources.
 *
 * @param handler instance of a CommandHandler for writing redis commands
 * @param connection implementation of a RedisConnection
 * @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
 *//* ww  w  . j a  va 2 s.c  o  m*/
protected void connectionBuilder(CommandHandler<?, ?> handler, RedisChannelHandler<?, ?> connection,
        Supplier<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,
            (int) socketOptions.getConnectTimeoutUnit().toMillis(socketOptions.getConnectTimeout()));

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

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

    connectionBuilder.bootstrap(redisBootstrap);
    connectionBuilder.channelGroup(channels).connectionEvents(connectionEvents).timer(timer);
    connectionBuilder.commandHandler(handler).socketAddressSupplier(socketAddressSupplier)
            .connection(connection);
    connectionBuilder.workerPool(genericWorkerPool);
}

From source file:com.lampard.netty4.protocol.netty.client.NettyClient.java

License:Apache License

public void connect(int port, String host) throws Exception {

    // ?NIO//from  w  w w.  j  av a2 s.  c o  m

    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new NettyMessageDecoder(1024 * 1024, 4, 4));
                        ch.pipeline().addLast("MessageEncoder", new NettyMessageEncoder());
                        ch.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(50));
                        ch.pipeline().addLast("LoginAuthHandler", new LoginAuthReqHandler());
                        ch.pipeline().addLast("HeartBeatHandler", new HeartBeatReqHandler());
                    }
                });
        // ??
        ChannelFuture future = b.connect(new InetSocketAddress(host, port),
                new InetSocketAddress(NettyConstant.LOCALIP, NettyConstant.LOCAL_PORT)).sync();
        // channelchannel
        // Returns the ChannelFuture which will be notified when this channel is closed. This method always returns the same future instance.
        future.channel().closeFuture().sync();
    } finally {
        // ????????
        executor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    TimeUnit.SECONDS.sleep(1);
                    try {
                        connect(NettyConstant.PORT, NettyConstant.REMOTEIP);// ???
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

From source file:com.lb.netty.protoc.SubReqClient.java

License:Apache License

public void connect(int port, String host) throws Exception {
    // ?NIO//w  w  w.ja v  a 2  s . c o m
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        System.out.println("12312312312312");
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        System.out.println("123123123123123");
                        ch.pipeline().addLast(new ProtobufVarint32FrameDecoder());
                        ch.pipeline().addLast(
                                new ProtobufDecoder(SubscribeReqProto.SubscribeReq.getDefaultInstance()));
                        ch.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender());
                        ch.pipeline().addLast(new ProtobufEncoder());
                        ch.pipeline().addLast(new SubReqClientHandler());
                    }
                });

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

From source file:com.linkedin.r2.transport.http.client.ChannelPoolLifecycle.java

License:Apache License

@Override
public void create(final Callback<Channel> channelCallback) {
    final long start = System.currentTimeMillis();
    _bootstrap.connect(_remoteAddress).addListener(new ChannelFutureListener() {
        @Override/*from w  ww . j  a  v a 2 s  .  co m*/
        public void operationComplete(ChannelFuture channelFuture) throws Exception {
            if (channelFuture.isSuccess()) {
                synchronized (_createTimeTracker) {
                    _createTimeTracker.addValue(System.currentTimeMillis() - start);
                }
                Channel c = channelFuture.channel();
                if (_tcpNoDelay) {
                    c.config().setOption(ChannelOption.TCP_NODELAY, true);
                }
                _channelGroup.add(c);
                channelCallback.onSuccess(c);
            } else {
                channelCallback.onError(HttpNettyStreamClient.toException(channelFuture.cause()));
            }
        }
    });
}

From source file:com.look.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  ww  w  .j av a  2s  . 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.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.ltln.modules.ni.omc.system.simulator.AlmClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    Constants.init();//from w ww .  j  av  a 2s . co  m
    final SslContext sslCtx;
    if (SSL) {
        sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    final EventExecutorGroup handlerGroup = new DefaultEventExecutorGroup(1);
    try {
        Bootstrap b = new Bootstrap();
        b.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();
                        if (sslCtx != null) {
                            p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT));
                        }
                        p.addLast(new AlarmMsgDecoder(8192, 7, 2, 0, 0, false));
                        p.addLast(new AlarmMsgEncoder());
                        p.addLast(handlerGroup, new AlarmClientHandler());
                    }
                });

        // Start the client.
        ChannelFuture f = b.connect(HOST, PORT).sync();

        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down the event loop to terminate all threads.
        group.shutdownGracefully();
    }
}

From source file:com.mapr.franz.netty.FranzClient.java

License:Apache License

public void run() throws Exception {
    // Configure the client.
    Bootstrap b = new Bootstrap();
    try {// ww w  . java2  s .c  o m
        b.group(new NioEventLoopGroup()).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                .remoteAddress(new InetSocketAddress(host, port))
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO),
                                new FranzClientHandler(firstMessageSize));
                    }
                });

        // Start the client.
        ChannelFuture f = b.connect().sync();

        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down the event loop to terminate all threads.
        b.shutdown();
    }
}

From source file:com.mapr.franz.netty.FranzServer.java

License:Apache License

public void run() throws Exception {
    // Configure the server.
    ServerBootstrap b = new ServerBootstrap();
    try {// w  w  w.j ava2  s  .  c  o  m
        b.group(new NioEventLoopGroup(), new NioEventLoopGroup()).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).localAddress(new InetSocketAddress(port))
                .childOption(ChannelOption.TCP_NODELAY, true).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO), new FranzServerHandler());
                    }
                });

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

        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        b.shutdown();
    }
}

From source file:com.mastfrog.netty.http.client.HttpClient.java

License:Open Source License

@SuppressWarnings("unchecked")
private synchronized Bootstrap start(HostAndPort hostAndPort) {
    if (bootstrap == null) {
        bootstrap = new Bootstrap();
        bootstrap.group(group);//from   w  w w  . java2  s  .  co  m
        bootstrap.handler(new Initializer(hostAndPort, handler, null, false, maxChunkSize, maxInitialLineLength,
                maxHeadersSize, compress));
        bootstrap.option(ChannelOption.TCP_NODELAY, true);
        bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
        bootstrap.option(ChannelOption.SO_REUSEADDR, false);
        if (timeout != null) {
            bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) timeout.getMillis());
        }
        for (ChannelOptionSetting<?> setting : settings) {
            option(bootstrap, setting);
        }
        bootstrap.channelFactory(new NioChannelFactory());
    }
    return bootstrap;
}