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.phei.netty.frame.fixedLen.TimeClient.java

License:Apache License

public void connect(int port, String host) throws Exception {
    // ?NIO//from w w  w  .j  a  va 2  s . 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(new FixedLengthFrameDecoder(20));
                        ch.pipeline().addLast(new StringDecoder());
                        ch.pipeline().addLast(new TimeClientHandler());
                    }
                });

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

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

From source file:com.phei.netty.protocol.http.xml.client.HttpXmlClient.java

License:Apache License

public void connect(int port) throws Exception {
    // ?NIO/*w  w  w. j a v a 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 {
                        //????http?
                        ch.pipeline().addLast("http-decoder", new HttpResponseDecoder());
                        //1Http????HTTP?
                        ch.pipeline().addLast("http-aggregator", new HttpObjectAggregator(65536));
                        // XML?
                        //http+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.quavo.osrs.network.NetworkExecutor.java

License:Open Source License

/**
 * Starts the network for a {@link Server}.
 * /*from   w  w  w. j  a v  a 2 s.  c o m*/
 * @param server The {@link Server} to use for building the network.
 * @return <True> If the network started successfully.
 */
public static void start() {
    EventLoopGroup boss = new NioEventLoopGroup();
    EventLoopGroup worker = new NioEventLoopGroup();
    ServerBootstrap bootstrap = new ServerBootstrap();

    bootstrap.group(boss, worker);
    bootstrap.channel(NioServerSocketChannel.class);
    bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();

            pipeline.addLast("decoder", new ConnectionDecoder());
            pipeline.addLast("encoder", new ConnectionEncoder());
            pipeline.addLast("adapter", new NetworkMessageHandler());
        }

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

    try {
        bootstrap.bind(Constants.HOST_NAME, Constants.HOST_PORT).sync();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    System.out.println("Server successfully bootstrapped on port " + Constants.HOST_PORT + " and address "
            + Constants.HOST_NAME + ".");
}

From source file:com.relayrides.pushy.apns.ApnsClient.java

License:Open Source License

protected ApnsClient(final SslContext sslContext, final EventLoopGroup eventLoopGroup) {
    this.bootstrap = new Bootstrap();

    if (eventLoopGroup != null) {
        this.bootstrap.group(eventLoopGroup);
        this.shouldShutDownEventLoopGroup = false;
    } else {/*from w  w  w  .j  a v  a2  s .  c  o m*/
        this.bootstrap.group(new NioEventLoopGroup(1));
        this.shouldShutDownEventLoopGroup = true;
    }

    this.bootstrap.channel(SocketChannelClassUtil.getSocketChannelClass(this.bootstrap.config().group()));
    this.bootstrap.option(ChannelOption.TCP_NODELAY, true);
    this.bootstrap.handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(final SocketChannel channel) throws Exception {
            final ChannelPipeline pipeline = channel.pipeline();

            final ProxyHandlerFactory proxyHandlerFactory = ApnsClient.this.proxyHandlerFactory;

            if (proxyHandlerFactory != null) {
                pipeline.addFirst(proxyHandlerFactory.createProxyHandler());
            }

            if (ApnsClient.this.writeTimeoutMillis > 0) {
                pipeline.addLast(
                        new WriteTimeoutHandler(ApnsClient.this.writeTimeoutMillis, TimeUnit.MILLISECONDS));
            }

            pipeline.addLast(sslContext.newHandler(channel.alloc()));
            pipeline.addLast(new ApplicationProtocolNegotiationHandler("") {
                @Override
                protected void configurePipeline(final ChannelHandlerContext context, final String protocol) {
                    if (ApplicationProtocolNames.HTTP_2.equals(protocol)) {
                        final ApnsClientHandler apnsClientHandler = new ApnsClientHandler.ApnsClientHandlerBuilder()
                                .server(false).apnsClient(ApnsClient.this)
                                .authority(
                                        ((InetSocketAddress) context.channel().remoteAddress()).getHostName())
                                .encoderEnforceMaxConcurrentStreams(true).build();

                        synchronized (ApnsClient.this.bootstrap) {
                            if (ApnsClient.this.gracefulShutdownTimeoutMillis != null) {
                                apnsClientHandler.gracefulShutdownTimeoutMillis(
                                        ApnsClient.this.gracefulShutdownTimeoutMillis);
                            }
                        }

                        context.pipeline().addLast(
                                new IdleStateHandler(0, 0, PING_IDLE_TIME_MILLIS, TimeUnit.MILLISECONDS));
                        context.pipeline().addLast(apnsClientHandler);

                        final ChannelPromise connectionReadyPromise = ApnsClient.this.connectionReadyPromise;

                        if (connectionReadyPromise != null) {
                            connectionReadyPromise.trySuccess();
                        }
                    } else {
                        throw new IllegalArgumentException("Unexpected protocol: " + protocol);
                    }
                }
            });
        }
    });
}

From source file:com.robert.NettyProject.EchoClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.git
    final SslContext sslCtx;
    if (SSL) {/* w ww  .  j  a v  a  2s.c om*/
        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("encode", new StringEncoder());
                        p.addLast("decode", new StringDecoder());
                        // p.addLast(new LoggingHandler(LogLevel.INFO));
                        p.addLast(new EchoClientHandler());
                    }
                });

        // Start the client.
        ChannelFuture f = b.connect(HOST, PORT).sync();
        Channel channel = f.channel();
        System.out.println("" + System.nanoTime());
        //         for(int i=0;i<10000;i++){            
        channel.writeAndFlush("hello");
        //         }

        // 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.rs3e.Main.java

License:Open Source License

/**
 * Initates a new gaming enviroment, here we are going to setup everything
 * needed for the server to be able to bind.
 *//*from  w  w w. j ava 2 s  . c  om*/
private void initate() {
    bootstrap = new ServerBootstrap();
    bootstrap.group(new NioEventLoopGroup(), new NioEventLoopGroup());
    bootstrap.channel(NioServerSocketChannel.class);
    bootstrap.option(ChannelOption.SO_BACKLOG, 100);
    bootstrap.childOption(ChannelOption.TCP_NODELAY, true);
    bootstrap.handler(new LoggingHandler(LogLevel.INFO));
    bootstrap.childHandler(new ChannelChildHandler(this));
    try {
        bootstrap.localAddress(Constants.ServerPort).bind().sync();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.sitech.crmpd.idmm2.ble.EchoClient.java

License:Apache License

public static void consumer(String[] args) throws Exception {
    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {//from   ww  w. j  a  v a 2 s  . 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(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new LoggingHandler(LogLevel.TRACE));
                        p.addLast(new FrameCodeC());
                        p.addLast(new ConsumerClientHandler(clientid, target_topic));
                    }
                });

        // Start the client.
        ChannelFuture f = b.connect(ble_ip, ble_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.sitech.crmpd.idmm2.ble.EchoClient.java

License:Apache License

public static void producer(String[] args) throws Exception {
    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {//from   w  w  w  . j a  va  2s. c om
        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 LoggingHandler(LogLevel.TRACE));
                        p.addLast(new FrameCodeC());
                        p.addLast(new ProducerClientHandler(clientid, target_topic));
                    }
                });

        // Start the client.
        ChannelFuture f = b.connect(ble_ip, ble_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.slyak.services.proxy.server.NettyProxyServer.java

License:Apache License

@SneakyThrows(InterruptedException.class)
public void start() {
    ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.ADVANCED);
    ServerBootstrap bootstrap = new ServerBootstrap();
    bossGroup = new NioEventLoopGroup(proxyProperties.getBoss());
    workerGroup = new NioEventLoopGroup(proxyProperties.getWorker());
    clientGroup = new NioEventLoopGroup(proxyProperties.getClient());
    try {//ww  w  .j  a  v  a2s  . c o  m
        bootstrap.group(bossGroup, workerGroup).channel(getChannelClass())
                .option(ChannelOption.SO_BACKLOG, proxyProperties.getBackLog())
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, proxyProperties.getConnectTimeout())

                .childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_REUSEADDR, true)

                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        //channel time out handler
                        pipeline.addLast(new IdleStateHandler(0, 0, 30));
                        pipeline.addLast(new IdleEventHandler());
                        //logging
                        pipeline.addLast(new LoggingHandler());

                        if (isRouter()) {
                            pipeline.addLast(getProxyHandler(proxyProperties));
                        } else {
                            pipeline.addLast(getCustomChannelHandlers(clientGroup));
                        }
                        pipeline.addLast(ExceptionHandler.INSTANCE);
                    }
                });
        //start server
        ChannelFuture future = bootstrap.bind(proxyProperties.getPort()).sync();
        log.debug("Starting proxy server , port is {}", proxyProperties.getPort());
        future.channel().closeFuture().sync();
    } finally {
        stop();
    }
}

From source file:com.sohail.alam.http.server.SetupServer.java

License:Apache License

public void initialize() {
    final ServerBootstrap serverBootstrap = new ServerBootstrap();
    final EventLoopGroup boss = new NioEventLoopGroup();
    final EventLoopGroup worker = new NioEventLoopGroup();

    serverBootstrap.group(boss, worker).channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_BACKLOG, ServerProperties.PROP.SO_BACKLOG)
            .childOption(ChannelOption.TCP_NODELAY, ServerProperties.PROP.TCP_NODELAY)
            .childOption(ChannelOption.SO_KEEPALIVE, ServerProperties.PROP.SO_KEEPALIVE)
            .childOption(ChannelOption.SO_REUSEADDR, ServerProperties.PROP.SO_REUSEADDR)
            .childHandler(new HttpChannelInitializer());

    try {//ww w .  ja  v  a2 s  .c  om
        ChannelFuture future = serverBootstrap.bind(new InetSocketAddress(ip, port)).sync();
        if (future.isSuccess()) {
            LoggerManager.LOGGER.info("Http Server Started Successfully @ {}:{}", ip, port);
        } else {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
            LoggerManager.LOGGER.fatal("Http Server Start Failed. Can not bind to {}:{}", ip, port);
        }
    } catch (Exception e) {
        LoggerManager.LOGGER.fatal("Exception Caught while starting Http Server", e);
    }

}