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.mpush.netty.client.NettyClient.java

License:Apache License

@Override
public void start(final Listener listener) {
    if (started.compareAndSet(false, true)) {
        Bootstrap bootstrap = new Bootstrap();
        workerGroup = new NioEventLoopGroup();
        bootstrap.group(workerGroup)//
                .option(ChannelOption.TCP_NODELAY, true)//
                .option(ChannelOption.SO_REUSEADDR, true)//
                .option(ChannelOption.SO_KEEPALIVE, true)//
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)//
                .channel(NioSocketChannel.class).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 4000);

        bootstrap.handler(new ChannelInitializer<SocketChannel>() { // (4)
            @Override/*  w w w . ja v  a2 s .c om*/
            public void initChannel(SocketChannel ch) throws Exception {
                initPipeline(ch.pipeline());
            }
        });

        ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
        future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    if (listener != null)
                        listener.onSuccess(port);
                    LOGGER.info("start netty client success, host={}, port={}", host, port);
                } else {
                    if (listener != null)
                        listener.onFailure(future.cause());
                    LOGGER.error("start netty client failure, host={}, port={}", host, port, future.cause());
                }
            }
        });
    } else {
        listener.onFailure(new ServiceException("client has started!"));
    }
}

From source file:com.mpush.netty.client.NettyTCPClient.java

License:Apache License

protected void initOptions(Bootstrap b) {
    b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 4000);
    b.option(ChannelOption.TCP_NODELAY, true);
}

From source file:com.mpush.netty.http.NettyHttpClient.java

License:Apache License

@Override
protected void doStart(Listener listener) throws Throwable {
    workerGroup = new NioEventLoopGroup(http_work, new DefaultThreadFactory(ThreadNames.T_HTTP_CLIENT));
    b = new Bootstrap();
    b.group(workerGroup);/*from w w w.j a  va  2  s  . c om*/
    b.channel(NioSocketChannel.class);
    b.option(ChannelOption.SO_KEEPALIVE, true);
    b.option(ChannelOption.TCP_NODELAY, true);
    b.option(ChannelOption.SO_REUSEADDR, true);
    b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 4000);
    b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    b.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast("decoder", new HttpResponseDecoder());
            ch.pipeline().addLast("aggregator", new HttpObjectAggregator(maxContentLength));
            ch.pipeline().addLast("encoder", new HttpRequestEncoder());
            ch.pipeline().addLast("handler", new HttpClientHandler(NettyHttpClient.this));
        }
    });
    timer = new HashedWheelTimer(new NamedThreadFactory(T_HTTP_TIMER), 1, TimeUnit.SECONDS, 64);
    listener.onSuccess();
}

From source file:com.mpush.test.client.ConnClientBoot.java

License:Apache License

@Override
protected void doStart(Listener listener) throws Throwable {
    ServiceDiscoveryFactory.create().syncStart();
    CacheManagerFactory.create().init();

    this.workerGroup = new NioEventLoopGroup();
    this.bootstrap = new Bootstrap();
    bootstrap.group(workerGroup)//
            .option(ChannelOption.TCP_NODELAY, true)//
            .option(ChannelOption.SO_REUSEADDR, true)//
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)//
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 60 * 1000)
            .option(ChannelOption.SO_RCVBUF, 5 * 1024 * 1024).channel(NioSocketChannel.class);

    bootstrap.handler(new ChannelInitializer<SocketChannel>() { // (4)
        @Override/*from   www .j a  va  2  s .  com*/
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast("decoder", new PacketDecoder());
            ch.pipeline().addLast("encoder", PacketEncoder.INSTANCE);
            ch.pipeline().addLast("handler", new ConnClientChannelHandler());
        }
    });

    listener.onSuccess();
}

From source file:com.nanxiaoqiang.test.netty.protocol.demo1.client.NettyClient.java

License:Apache License

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

    // ?NIO//from   ww  w.  j  ava  2 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();
        // 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.navercorp.nbasearc.gcp.PhysicalConnection.java

License:Apache License

static PhysicalConnection create(String ip, int port, SingleThreadEventLoop eventLoop, Gateway gw,
        int reconnectInterval) {
    final PhysicalConnection pc = new PhysicalConnection(ip, port, eventLoop, gw, reconnectInterval);

    pc.b.group(eventLoop.getEventLoopGroup()).channel(NioSocketChannel.class)
            .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_REUSEADDR, true)
            .option(ChannelOption.SO_KEEPALIVE, true).option(ChannelOption.SO_LINGER, 0)
            .option(ChannelOption.SO_SNDBUF, SOCKET_BUFFER).option(ChannelOption.SO_RCVBUF, SOCKET_BUFFER)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override//  w ww  .  j a  v  a 2  s.c  o m
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(pc.new PhysicalConnectionHandler());
                }
            });

    return pc;
}

From source file:com.navercorp.pinpoint.grpc.client.ChannelFactory.java

License:Apache License

private void setupClientOption(final NettyChannelBuilder channelBuilder) {
    channelBuilder.keepAliveTime(clientOption.getKeepAliveTime(), TimeUnit.MILLISECONDS);
    channelBuilder.keepAliveTimeout(clientOption.getKeepAliveTimeout(), TimeUnit.MILLISECONDS);
    channelBuilder.keepAliveWithoutCalls(clientOption.isKeepAliveWithoutCalls());
    channelBuilder.maxHeaderListSize(clientOption.getMaxHeaderListSize());
    channelBuilder.maxInboundMessageSize(clientOption.getMaxInboundMessageSize());

    // ChannelOption
    channelBuilder.withOption(ChannelOption.TCP_NODELAY, true);
    channelBuilder.withOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, clientOption.getConnectTimeout());
    final WriteBufferWaterMark writeBufferWaterMark = new WriteBufferWaterMark(
            clientOption.getWriteBufferLowWaterMark(), clientOption.getWriteBufferHighWaterMark());
    channelBuilder.withOption(ChannelOption.WRITE_BUFFER_WATER_MARK, writeBufferWaterMark);
    if (logger.isInfoEnabled()) {
        logger.info("Set clientOption {}. name={}", clientOption, name);
    }/* w w  w .j  a va 2 s .c o  m*/
}

From source file:com.navercorp.pinpoint.grpc.server.ServerFactory.java

License:Apache License

private void setupServerOption(final NettyServerBuilder builder) {
    // TODO @see PinpointServerAcceptor
    builder.withChildOption(ChannelOption.TCP_NODELAY, true);
    builder.withChildOption(ChannelOption.SO_REUSEADDR, true);
    builder.withChildOption(ChannelOption.SO_RCVBUF, this.serverOption.getReceiveBufferSize());
    builder.withChildOption(ChannelOption.SO_BACKLOG, this.serverOption.getBacklogQueueSize());
    builder.withChildOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, this.serverOption.getConnectTimeout());
    final WriteBufferWaterMark writeBufferWaterMark = new WriteBufferWaterMark(
            this.serverOption.getWriteBufferLowWaterMark(), this.serverOption.getWriteBufferHighWaterMark());
    builder.withChildOption(ChannelOption.WRITE_BUFFER_WATER_MARK, writeBufferWaterMark);

    builder.handshakeTimeout(this.serverOption.getHandshakeTimeout(), TimeUnit.MILLISECONDS);
    builder.flowControlWindow(this.serverOption.getFlowControlWindow());

    builder.maxInboundMessageSize(this.serverOption.getMaxInboundMessageSize());
    builder.maxHeaderListSize(this.serverOption.getMaxHeaderListSize());

    builder.keepAliveTime(this.serverOption.getKeepAliveTime(), TimeUnit.MILLISECONDS);
    builder.keepAliveTimeout(this.serverOption.getKeepAliveTimeout(), TimeUnit.MILLISECONDS);
    builder.permitKeepAliveTime(this.serverOption.getPermitKeepAliveTimeout(), TimeUnit.MILLISECONDS);
    builder.permitKeepAliveWithoutCalls(this.serverOption.isPermitKeepAliveWithoutCalls());

    builder.maxConnectionIdle(this.serverOption.getMaxConnectionIdle(), TimeUnit.MILLISECONDS);
    builder.maxConnectionAge(this.serverOption.getMaxConnectionAge(), TimeUnit.MILLISECONDS);
    builder.maxConnectionAgeGrace(this.serverOption.getMaxConnectionAgeGrace(), TimeUnit.MILLISECONDS);
    builder.maxConcurrentCallsPerConnection(this.serverOption.getMaxConcurrentCallsPerConnection());
    if (logger.isInfoEnabled()) {
        logger.info("Set serverOption {}. name={}, hostname={}, port={}", serverOption, name, hostname, port);
    }//w  w  w .ja v a  2 s.  c  o m
}

From source file:com.netty.fileTest.file.FileReaderClient.java

License:Apache License

public static void main(String[] args) throws Exception {

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {/*  ww  w  .  ja v  a  2  s  . com*/
        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();
                        p.addLast(new FileReaderClientHandler());
                    }
                });

        // Start the client.
        ChannelFuture f = b.connect("127.0.0.1", 8007).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.newlandframework.avatarmq.broker.server.AvatarMQBrokerServer.java

License:Apache License

public void init() {
    try {//from   www.  j a  va2s .c o m
        handler = new MessageBrokerHandler().buildConsumerHook(new ConsumerMessageHook())
                .buildProducerHook(new ProducerMessageHook());

        boss = new NioEventLoopGroup(1, threadBossFactory);

        workers = new NioEventLoopGroup(parallel, threadWorkerFactory, NettyUtil.getNioSelectorProvider());

        KryoCodecUtil util = new KryoCodecUtil(KryoPoolFactory.getKryoPoolInstance());

        bootstrap = new ServerBootstrap();

        bootstrap.group(boss, workers).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, nettyClustersConfig.getClientSocketSndBufSize())
                .option(ChannelOption.SO_RCVBUF, nettyClustersConfig.getClientSocketRcvBufSize())
                .handler(new LoggingHandler(LogLevel.INFO)).localAddress(serverIpAddr)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(defaultEventExecutorGroup, new MessageObjectEncoder(util),
                                new MessageObjectDecoder(util), handler);
                    }
                });

        super.init();
    } catch (IOException ex) {
        Logger.getLogger(AvatarMQBrokerServer.class.getName()).log(Level.SEVERE, null, ex);
    }
}