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:cc.ly.mc.core.server.io.SocketServer.java

License:Apache License

public void run() {
    // Configure the server.
    bossGroup = new NioEventLoopGroup(1);
    workerGroup = new NioEventLoopGroup();
    try {//w w  w  .  j a  v  a  2 s . co  m
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).option(ChannelOption.SO_REUSEADDR, true)
                .option(ChannelOption.TCP_NODELAY, true)
                .childHandler(new SocketServerInitializer(connectedListeners, disconnectedListeners));
        // Start the server.
        // Wait until the server socket is closed.
        try {
            b.bind(port).sync().channel().closeFuture().sync();
        } catch (InterruptedException e) {
        }
    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:cc.ly.mc.server.netty.SocketServer.java

License:Apache License

public void run() {
    // Configure the server.
    bossGroup = new NioEventLoopGroup(1);
    workerGroup = new NioEventLoopGroup();
    try {//from  ww w .  ja  v  a2  s.co  m
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).option(ChannelOption.SO_REUSEADDR, true)
                .option(ChannelOption.TCP_NODELAY, true).childHandler(new SocketServerInitializer());
        // Start the server.
        // Wait until the server socket is closed.
        try {
            b.bind(port).sync().channel().closeFuture().sync();
        } catch (InterruptedException e) {
        }
    } finally {
        // Shut down all event loops to terminate all threads.
        close();
    }
}

From source file:cc.sharper.netty.delimiter.EchoClient.java

License:Apache License

public void connect(int port, String host) throws Exception {
    // ?NIO/*w  ww  . jav  a2s  . 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 {
                        //? 
                        ByteBuf delimiter = Unpooled.copiedBuffer("$_".getBytes());
                        ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter));

                        ch.pipeline().addLast(new StringDecoder());
                        ch.pipeline().addLast(new EchoClientHandler());
                    }
                });

        // ??
        ChannelFuture f = b.connect(host, port).sync();

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

From source file:cc.sharper.netty.TimeClient.java

License:Apache License

public void connect(int port, String host) throws Exception {
    // ?NIO//from w ww .ja  va 2  s.  c om
    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(new TimeClientHandler());
                    }
                });

        // ??
        ChannelFuture f = b.connect(host, port).sync();

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

From source file:club.jmint.crossing.client.CrossingClient.java

License:Apache License

public void startup() throws CrossException {
    SslContext sslCtx = null;//ww  w .  ja v a 2  s.c o m
    if (isSSLEnabled) {
        try {
            sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
        } catch (Exception e) {
            CrossLog.printStackTrace(e);
            throw new CrossException(ErrorCode.CROSSING_ERR_CLIENT_STARTUP.getCode(),
                    ErrorCode.CROSSING_ERR_CLIENT_STARTUP.getInfo());
        }
    } else {
        sslCtx = null;
    }

    // Configure the client.
    group = new NioEventLoopGroup();
    try {
        bs = new Bootstrap();
        bs.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                .handler(new ClientChannelInitializer(sslCtx, chandler));

        // Start the client.
        cf = bs.connect(ip, port).sync();
        channel = cf.channel();

        // Wait until the connection is closed.
        //f.channel().closeFuture().sync();
    } catch (Exception e) {
        CrossLog.printStackTrace(e);
        throw new CrossException(ErrorCode.CROSSING_ERR_CLIENT_STARTUP.getCode(),
                ErrorCode.CROSSING_ERR_CLIENT_STARTUP.getInfo());

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

    ccall = new CrossingCall(cf, chandler, config);
    CrossLog.logger.info("Crossing Client started.");
}

From source file:cn.david.main.EchoClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.git
    final SslContext sslCtx;
    if (SSL) {//ww  w. ja  va2  s .  com
        sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
    } 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:cn.scujcc.bug.bitcoinplatformandroid.util.socket.websocket.WebSocketBase.java

License:Apache License

private void connect() {
    try {//www.ja  v  a 2  s  . c o m
        final URI uri = new URI(url);
        if (uri == null) {
            return;
        }
        if (uri.getHost().contains("com")) {
            siteFlag = 1;
        }
        group = new NioEventLoopGroup(1);
        bootstrap = new Bootstrap();
        final SslContext sslCtx = SslContext.newClientContext();
        final WebSocketClientHandler handler = new WebSocketClientHandler(
                WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, null, false,
                        new DefaultHttpHeaders(), Integer.MAX_VALUE),
                service, moniter);
        bootstrap.group(group).option(ChannelOption.TCP_NODELAY, true).channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel ch) {
                        ChannelPipeline p = ch.pipeline();
                        if (sslCtx != null) {
                            p.addLast(sslCtx.newHandler(ch.alloc(), uri.getHost(), uri.getPort()));
                        }
                        p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192), handler);
                    }
                });

        future = bootstrap.connect(uri.getHost(), uri.getPort());
        future.addListener(new ChannelFutureListener() {
            public void operationComplete(final ChannelFuture future) throws Exception {
            }
        });
        channel = future.sync().channel();
        handler.handshakeFuture().sync();
        this.setStatus(true);
    } catch (Exception e) {
        Log.e(TAG, "WebSocketClient start error " + e.getLocalizedMessage());
        group.shutdownGracefully();
        this.setStatus(false);
    }
}

From source file:cn.yesway.demo.book.protocol.http.xml.client.HttpXmlClient.java

License:Apache License

public void connect(int port) throws Exception {
    // ?NIO/*from w  ww  . j  av  a2s  .  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:code.google.nfs.rpc.netty.client.NettyClientFactory.java

License:Apache License

protected Client createClient(String targetIP, int targetPort, int connectTimeout, String key)
        throws Exception {
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(workerGroup).channel(NioSocketChannel.class)
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .option(ChannelOption.TCP_NODELAY,
                    Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.nodelay", "true")))
            .option(ChannelOption.SO_REUSEADDR,
                    Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.reuseaddress", "true")));
    if (connectTimeout < 1000) {
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000);
    } else {/*from   ww w .j  a va2  s  .  co m*/
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout);
    }
    final NettyClientHandler handler = new NettyClientHandler(this, key);
    bootstrap.handler(new ChannelInitializer<SocketChannel>() {

        protected void initChannel(SocketChannel channel) throws Exception {
            ChannelPipeline pipeline = channel.pipeline();
            pipeline.addLast("decoder", new NettyProtocolDecoder());
            pipeline.addLast("encoder", new NettyProtocolEncoder());
            pipeline.addLast("handler", handler);
        }

    });
    ChannelFuture future = bootstrap.connect(new InetSocketAddress(targetIP, targetPort)).sync();
    future.awaitUninterruptibly(connectTimeout);
    if (!future.isDone()) {
        LOGGER.error("Create connection to " + targetIP + ":" + targetPort + " timeout!");
        throw new Exception("Create connection to " + targetIP + ":" + targetPort + " timeout!");
    }
    if (future.isCancelled()) {
        LOGGER.error("Create connection to " + targetIP + ":" + targetPort + " cancelled by user!");
        throw new Exception("Create connection to " + targetIP + ":" + targetPort + " cancelled by user!");
    }
    if (!future.isSuccess()) {
        LOGGER.error("Create connection to " + targetIP + ":" + targetPort + " error", future.cause());
        throw new Exception("Create connection to " + targetIP + ":" + targetPort + " error", future.cause());
    }
    NettyClient client = new NettyClient(future, key, connectTimeout);
    handler.setClient(client);
    return client;
}

From source file:code.google.nfs.rpc.netty.server.NettyServer.java

License:Apache License

public NettyServer() {
    ThreadFactory serverBossTF = new NamedThreadFactory("NETTYSERVER-BOSS-");
    ThreadFactory serverWorkerTF = new NamedThreadFactory("NETTYSERVER-WORKER-");
    EventLoopGroup bossGroup = new NioEventLoopGroup(PROCESSORS, serverBossTF);
    NioEventLoopGroup workerGroup = new NioEventLoopGroup(PROCESSORS * 2, serverWorkerTF);
    workerGroup.setIoRatio(Integer.parseInt(System.getProperty("nfs.rpc.io.ratio", "50")));
    bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .option(ChannelOption.SO_REUSEADDR,
                    Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.reuseaddress", "true")))
            .option(ChannelOption.TCP_NODELAY,
                    Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.nodelay", "true")));
}