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:net.tridentsdk.server.netty.ClientChannelInitializer.java

License:Open Source License

@Override
protected void initChannel(SocketChannel channel) throws Exception {
    //channel.config().setOption(ChannelOption.IP_TOS, 24);
    channel.config().setOption(ChannelOption.TCP_NODELAY, true);

    this.connection = ClientConnection.registerConnection(channel);

    //Decode:/*w ww.ja  v a 2  s.c  o m*/
    channel.pipeline().addLast(new PacketDecrypter());
    channel.pipeline().addLast(new PacketDecoder());
    channel.pipeline().addLast(new PacketHandler());

    //Encode:
    channel.pipeline().addLast(new PacketEncrypter());
    channel.pipeline().addLast(new PacketEncoder());
}

From source file:net.tridentsdk.server.TridentStart.java

License:Open Source License

/**
 * Initializes the server with the configuration file
 *
 * @param config the configuration to use for option lookup
 *//* ww w.  j a  v a2 s .  co m*/
private static void init(JsonConfig config) {
    //TODO: Need to run on seperate thread?
    //Server should read all settings from the loaded config
    final ConcurrentTaskExecutor<?> taskExecutor = new ConcurrentTaskExecutor<>(1);
    final JsonConfig innerConfig = config;

    LOGGER.info("Creating server task thread...");
    taskExecutor.getScaledThread().addTask(new Runnable() {
        @Override
        public void run() {
            TridentServer.createServer(innerConfig, taskExecutor, LOGGER);
        }
    });

    try {
        LOGGER.info("Creating server connections...");
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ClientChannelInitializer()).option(ChannelOption.TCP_NODELAY, true);

        // Bind and start to accept incoming connections.
        int port = config.getInt("port", 25565);
        LOGGER.info("Binding socket to server address, using port: " + port);
        ChannelFuture f = b.bind(new InetSocketAddress(config.getString("address", Defaults.ADDRESS),
                config.getInt("port", Defaults.PORT))).sync();

        // Wait until the server socket is closed, to gracefully shut down your server.
        LOGGER.info("Server started!");
        f.channel().closeFuture().sync();
    } catch (InterruptedException e) {
        //This exception is caught if server is closed.
    } catch (Exception e) {
        LOGGER.error("Server closed, error occurred");
        LOGGER.error("Printing stacktrace: \n");
        e.printStackTrace();
    } finally {
        LOGGER.info("Server shutting down...");
        TridentServer.getInstance().shutdown();
    }
}

From source file:netty.client.http.NettyHelloWorldClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.git
    final SslContext sslCtx;
    if (SSL) {//from   ww w.  ja v  a2  s  . c om
        sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    NettyResponseLogger loggingHandler = new NettyResponseLogger();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                .remoteAddress(HOST, PORT).handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        //p.addLast(new LoggingHandler(LogLevel.INFO));
                        p.addLast(new HttpClientCodec());
                        p.addLast(loggingHandler);
                    }
                });

        // Start the client.
        Channel channel = b.connect().syncUninterruptibly().channel();

        channel.writeAndFlush(new DefaultFullHttpRequest(HTTP_1_1, GET, URL)).syncUninterruptibly();
        Thread.sleep(5000);
        channel.writeAndFlush(new DefaultFullHttpRequest(HTTP_1_1, GET, URL)).syncUninterruptibly();
        Thread.sleep(5000);
        channel.writeAndFlush(new DefaultFullHttpRequest(HTTP_1_1, GET, URL)).syncUninterruptibly();

        // Wait until the connection is closed.
        System.err.println("Waiting for connection to be closed.");
        channel.closeFuture().sync();
    } finally {
        // Shut down the event loop to terminate all threads.
        group.shutdownGracefully();
    }
}

From source file:netty.codec.marshalling.SubReqClient.java

License:Apache License

public void connect(int port, String host) throws Exception {
    // ?NIO/*from   ww  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)
                .remoteAddress(new InetSocketAddress(host, port))
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingDecoder());
                        ch.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingEncoder());
                        ch.pipeline().addLast("clientHandler", new SubReqClientHandler());
                    }
                });

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

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

From source file:netty.codec.protobuf.SubReqClient.java

License:Apache License

public void connect(int port, String host) throws Exception {
    // ?NIO//from   w  w  w .j a v a  2s. 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 ProtobufVarint32FrameDecoder());
                        // ????
                        ch.pipeline().addLast(
                                new ProtobufDecoder(SubscribeRespProto.SubscribeResp.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:netty.protocol.echo.EchoClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    PropertyConfigurator.configure("log4j.properties");
    // Configure SSL.git
    final SslContext sslCtx;
    if (SSL) {//from  w  ww  . j  av a  2 s .c  om
        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:netty.server.Server.java

License:Apache License

public void run() throws CertificateException, SSLException, UnknownHostException {

    final BlockingQueue<String> qq = new LinkedBlockingQueue<>(1);

    bossGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup();
    try {/*from ww  w .  ja va  2  s.  c  o  m*/
        final ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).option(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.SO_KEEPALIVE, true).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(final SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        //                            p.addLast(new LoggingHandler(LogLevel.INFO));
                        p.addLast(new WebSocketServerInitializer(qq));
                    }
                });

        try {
            //                channelFuture = b.bind(port).sync().await();
            //                System.out.println(Server.class.getName() +
            //                        " started and listen on " + channelFuture.channel().localAddress());
            //                InetAddress address = InetAddress.getByName("192.168.1.152");
            channelFuture = b.bind(port).sync().await();
            System.out.println(Server.class.getName() + " started and listen on "
                    + channelFuture.channel().localAddress());
            System.out.println("Web socket server started at port " + port + '.');
            //                System.out.println("Open your browser and navigate to http " + port + '/');
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException ex) {
            ex.printStackTrace();
            logger.error("InterruptedException " + ex.getLocalizedMessage());
        }

        // Wait until the server socket is closed.
        try {
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }

    } finally {
        close();
    }
}

From source file:nettyechoclientdemo.EchoClient.java

public void connect(int port, String host) throws InterruptedException {
    EventLoopGroup group = new NioEventLoopGroup();

    try {/*from w w w  .j a v a  2 s  .  c  om*/
        Bootstrap bootstrap = new Bootstrap();

        bootstrap.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel c) throws Exception {
                        ByteBuf delimiter = Unpooled.copiedBuffer("$_".getBytes());
                        c.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter));
                        c.pipeline().addLast(new StringDecoder());
                        c.pipeline().addLast(new EchoClientHandler());
                    } //initChannel()                
                });

        ChannelFuture future = bootstrap.connect(host, port).sync();

        future.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    } //try-finally

}

From source file:nettyjavaserializationclientdemo.SubReqClient.java

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

    EventLoopGroup group = new NioEventLoopGroup();

    try {/* w w w. j  a  v a2s .c o m*/

        Bootstrap bootstrap = new Bootstrap();

        bootstrap.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel c) throws Exception {
                        c.pipeline().addLast(new ObjectDecoder(1024,
                                ClassResolvers.cacheDisabled(this.getClass().getClassLoader())));
                        c.pipeline().addLast(new ObjectEncoder());
                        c.pipeline().addLast(new SubReqClientHandler());
                    } //initChannel()

                });

        ChannelFuture future = bootstrap.connect(host, port).sync();

        future.channel().closeFuture().sync();

    } finally {
        group.shutdownGracefully();
    }

}

From source file:nettyjbossmarshallingclientdemo.SubReqClient.java

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

    EventLoopGroup group = new NioEventLoopGroup();

    try {/*  ww  w.j a v a2s . co m*/

        Bootstrap bootstrap = new Bootstrap();

        bootstrap.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel c) throws Exception {
                        c.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingDecoder());
                        c.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingEncoder());
                        c.pipeline().addLast(new SubReqClientHandler());
                    } //initChannel()

                });

        ChannelFuture future = bootstrap.connect(host, port).sync();

        future.channel().closeFuture().sync();

    } finally {
        group.shutdownGracefully();
    }

}