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.hipishare.chat.test.EchoClient.java

License:Apache License

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

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    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 LoggingHandler(LogLevel.INFO));
                        p.addLast(new EchoClientHandler());
                    }
                });

        // 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.hxr.javatone.concurrency.netty.official.echo.EchoClient.java

License:Apache License

public void run() throws Exception {
    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {//from w w  w .  jav a2s  .  co  m
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(final SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(
                                //new LoggingHandler(LogLevel.INFO),
                                new EchoClientHandler(firstMessageSize));
                    }
                });

        // 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.ibasco.agql.protocols.valve.source.query.SourceRconMessenger.java

License:Open Source License

@Override
protected Transport<SourceRconRequest> createTransportService() {
    NettyPooledTcpTransport<SourceRconRequest> transport = new NettyPooledTcpTransport<>(ChannelType.NIO_TCP);
    transport.setChannelInitializer(new SourceRconChannelInitializer(this));
    transport.addChannelOption(ChannelOption.SO_SNDBUF, 1048576 * 4);
    transport.addChannelOption(ChannelOption.SO_RCVBUF, 1048576 * 4);
    transport.addChannelOption(ChannelOption.SO_KEEPALIVE, true);
    transport.addChannelOption(ChannelOption.TCP_NODELAY, true);
    return transport;
}

From source file:com.ict.dtube.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 ww .ja  v  a2s.co m*/
                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_SNDBUF, NettySystemConfig.SocketSndbufSize)
            //
            .option(ChannelOption.SO_RCVBUF, NettySystemConfig.SocketRcvbufSize)
            //
            .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.ict.dtube.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//from   w ww.java 2 s . c  o m
                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)
                    //
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    //
                    .childOption(ChannelOption.SO_SNDBUF, NettySystemConfig.SocketSndbufSize)
                    //
                    .childOption(ChannelOption.SO_RCVBUF, NettySystemConfig.SocketRcvbufSize)

                    .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 (NettySystemConfig.NettyPooledByteBufAllocatorEnable) {
        // ????
        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.jjzhk.Chapter10.xml.HttpXmlClient.java

License:Apache License

public void connect(int port) throws Exception {
    // ?NIO?//from ww  w .jav  a  2s. c o  m
    EventLoopGroup group = new NioEventLoopGroup();
    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("http-decoder", new HttpResponseDecoder());
                        ch.pipeline().addLast("http-aggregator", new HttpObjectAggregator(65536));
                        // XML??
                        ch.pipeline().addLast("xml-decoder", new HttpXmlResponseDecoder(Order.class, true));
                        ch.pipeline().addLast("http-encoder", new HttpRequestEncoder());
                        ch.pipeline().addLast("xml-encoder", new HttpXmlRequestEncoder());
                        ch.pipeline().addLast("xmlClientHandler", new HttpXmlClientHandle());
                    }
                });

        // ??
        ChannelFuture f = b.connect(new InetSocketAddress(port)).sync();

        // ?
        f.channel().closeFuture().sync();
    } finally {
        // ?NIO?
        group.shutdownGracefully();
    }
}

From source file:com.jjzhk.Chapter14.netty.NettyClient.java

License:Apache License

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

    try {//from  w  w  w  . ja va2s .c o  m
        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() {
            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.kevinherron.GatewayHook.java

@Override
public void startup(LicenseState licenseState) {
    logger.info("startup()");

    try {/*  ww  w.  ja v  a  2  s.  c  o  m*/
        Bootstrap bootstrap = new Bootstrap();

        bootstrap.group(eventLoop).channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000).option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        logger.info("initChannel");
                    }
                });

        bootstrap.connect("localhost", 1234).get(2, TimeUnit.SECONDS);
    } catch (Throwable t) {
        logger.error("failed getting un-gettable endpoints: {}", t.getMessage(), t);
    }
}

From source file:com.kixeye.kixmpp.client.KixmppClient.java

License:Apache License

/**
 * Creates a new {@link KixmppClient}./*from ww  w .  j a v a  2 s . com*/
 * 
 * @param eventLoopGroup
 * @param eventEngine
 * @param sslContext
 * @param type
 */
public KixmppClient(EventLoopGroup eventLoopGroup, KixmppEventEngine eventEngine, SslContext sslContext,
        Type type) {
    if (sslContext != null) {
        assert sslContext.isClient() : "The given SslContext must be a client context.";
    }

    if (eventLoopGroup == null) {
        if (OS.indexOf("nux") >= 0) {
            eventLoopGroup = new EpollEventLoopGroup();
        } else {
            eventLoopGroup = new NioEventLoopGroup();
        }
    }

    this.type = type;

    this.sslContext = sslContext;
    this.eventEngine = eventEngine;

    // set modules to be registered
    this.modulesToRegister.add(MucKixmppClientModule.class.getName());
    this.modulesToRegister.add(PresenceKixmppClientModule.class.getName());
    this.modulesToRegister.add(MessageKixmppClientModule.class.getName());
    this.modulesToRegister.add(ErrorKixmppClientModule.class.getName());

    if (eventLoopGroup instanceof EpollEventLoopGroup) {
        this.bootstrap = new Bootstrap().group(eventLoopGroup).channel(EpollSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, false).option(ChannelOption.SO_KEEPALIVE, true);
    } else {
        this.bootstrap = new Bootstrap().group(eventLoopGroup).channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, false).option(ChannelOption.SO_KEEPALIVE, true);
    }

    switch (type) {
    case TCP:
        bootstrap.handler(new KixmppClientChannelInitializer());
        break;
    case WEBSOCKET:
        bootstrap.handler(new KixmppClientWebSocketChannelInitializer());
        break;
    }
}

From source file:com.kixeye.kixmpp.p2p.node.NodeClient.java

License:Apache License

public void initialize(final String host, int port, final EventLoopGroup workerGroup,
        final MessageRegistry messageRegistry, final ChannelInboundHandlerAdapter channelListener)
        throws InterruptedException {
    // prepare connection
    Bootstrap boot = new Bootstrap();
    boot.group(workerGroup);//  w  ww.  j  ava  2s  .  c o  m
    boot.channel(NioSocketChannel.class);
    boot.option(ChannelOption.SO_KEEPALIVE, true);
    boot.option(ChannelOption.TCP_NODELAY, true);
    boot.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected 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);
        }
    });

    // connect
    channel = boot.connect(host, port).sync().channel();
}