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.stremebase.examples.todomvc.Todo.java

License:Apache License

public static void main(String[] args) throws Exception {
    css = new String(Files.readAllBytes(Paths.get(System.getProperty("user.dir"), "Web", "index.css")));
    favicon = Files.readAllBytes(Paths.get(System.getProperty("user.dir"), "Web", "favicon.ico"));

    Table.setDefaultDb(new DB("user.dir"));
    data = new Data(itemTableId, "ITEMTABLE");

    @SuppressWarnings("unchecked")
    Router<Integer> router = new Router<Integer>().GET("/", GET).GET("/filter/:filtertype", FILTER)

            .POST("/", POST).POST("/delete", DELETE).POST("/clearcompleted", DELETECOMPLETED)
            .POST("/toggle-status", TOGGLESTATUS)

            .GET(":something/index.css", CSS).GET("/index.css", CSS).GET("/favicon.ico", ICON)
            .notFound(NOTFOUND);//  w  w w .  j  a  v  a2s .co  m
    System.out.println(router);

    OioEventLoopGroup bossGroup = new OioEventLoopGroup(1);
    SingleThreadEventLoop workerGroup = new ThreadPerChannelEventLoop(bossGroup);

    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).childOption(ChannelOption.TCP_NODELAY, java.lang.Boolean.TRUE)
                .childOption(ChannelOption.SO_KEEPALIVE, java.lang.Boolean.TRUE)
                .childOption(ChannelOption.SO_REUSEADDR, java.lang.Boolean.TRUE)
                .channel(OioServerSocketChannel.class).childHandler(new HttpRouterServerInitializer(router));

        Channel ch = b.bind(PORT).sync().channel();
        System.out.println("Server started: http://127.0.0.1:" + PORT + '/');

        ch.closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.system.distribute.server.FileClient.java

License:Apache License

public ChannelFuture run() throws Exception {
    // Configure the server.
    final Bootstrap bootstrap = BootstrapFactory.createBootstrap(ChannelType.NIO);

    bootstrap.handler(new FileClientHandler());
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000);

    try {//from w  w  w  .j  a  v a  2 s.  c  om
        final ChannelFuture channelFuture = bootstrap.connect(new InetSocketAddress(host, port)).sync();
        channelFuture.awaitUninterruptibly();

    } catch (InterruptedException e) {

    }

    // Start the server.
    ChannelFuture f = bootstrap.bind(port).sync();

    // Wait until the server socket is closed.
    f.channel().closeFuture().sync();
    return f;

}

From source file:com.tc.websocket.server.DominoWebSocketServer.java

License:Apache License

@Override
public synchronized void start() {

    if (this.isOn())
        return;// www.  j a  v  a  2s  .  com

    try {
        try {

            ServerBootstrap boot = new ServerBootstrap();

            if (cfg.isNativeTransport()) {
                boot.channel(EpollServerSocketChannel.class);
            } else {
                boot.channel(NioServerSocketChannel.class);
            }

            boot.group(bossGroup, workerGroup).option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    .childOption(ChannelOption.WRITE_BUFFER_WATER_MARK,
                            new WriteBufferWaterMark(8 * 1024, 32 * 1024))
                    .childOption(ChannelOption.SO_SNDBUF, cfg.getSendBuffer())
                    .childOption(ChannelOption.SO_RCVBUF, cfg.getReceiveBuffer())
                    .childOption(ChannelOption.TCP_NODELAY, true).childHandler(init);

            //bind to the main port
            boot.bind(cfg.getPort()).sync();

            //bind to the redirect port (e.g. 80 will redirect to 443)
            for (Integer port : cfg.getRedirectPorts()) {
                ChannelFuture f = boot.bind(port);
                f.sync();
            }

            this.on.set(true);

            String version = BundleUtils.getVersion(Activator.bundle);
            String name = BundleUtils.getName(Activator.bundle);
            cfg.print(name + " ready and listening on " + cfg.getPort() + " running version " + version);

        } finally {

        }
    } catch (Exception e) {
        LOG.log(Level.SEVERE, null, e);
    }
}

From source file:com.tesora.dve.db.mysql.portal.MySqlPortal.java

License:Open Source License

public MySqlPortal(Properties props) throws PEException {
    // This is the port the Portal is going to listen on -
    // default to Mysql's port
    int port = Singletons.require(HostService.class).getPortalPort(props);
    Singletons.replace(MySqlPortalService.class, this);

    InternalLoggerFactory.setDefaultFactory(new Log4JLoggerFactory());

    int max_concurrent = KnownVariables.MAX_CONCURRENT.getValue(null).intValue();

    //TODO: parse/plan is on this pool, which is probably ok, especially with blocking calls to catalog.  Check for responses that can be done by backend netty threads and avoid two context shifts.

    clientExecutorService = new PEThreadPoolExecutor(max_concurrent, max_concurrent, 30L, TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>(), //The thread count limits concurrency here.  Using a bounded queue here would block netty threads (very bad), so this pool could be overrun by 'bad' clients that pipeline. -sgossard
            new PEDefaultThreadFactory("msp-client"));
    clientExecutorService.allowCoreThreadTimeOut(true);

    bossGroup = new NioEventLoopGroup(1, new PEDefaultThreadFactory("msp-boss"));

    //fixes the number of Netty NIO threads to the number of available CPUs.
    workerGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors(),
            new PEDefaultThreadFactory("netty-worker"));

    ServerBootstrap b = new ServerBootstrap();
    try {/*from w ww.  j a v  a 2  s. c o  m*/
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        if (PACKET_LOGGER)
                            ch.pipeline().addFirst(new LoggingHandler(LogLevel.INFO));
                        ch.pipeline()
                                .addLast(MSPProtocolDecoder.class.getSimpleName(),
                                        new MSPProtocolDecoder(
                                                MSPProtocolDecoder.MyDecoderState.READ_CLIENT_AUTH))
                                .addLast(new MSPAuthenticateHandlerV10())
                                .addLast(MSPCommandHandler.class.getSimpleName(),
                                        new MSPCommandHandler(clientExecutorService))
                                .addLast(ConnectionHandlerAdapter.getInstance());
                    }
                })

                .childOption(ChannelOption.ALLOCATOR,
                        USE_POOLED_BUFFERS ? PooledByteBufAllocator.DEFAULT : UnpooledByteBufAllocator.DEFAULT)
                .childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true)
                .bind(port).sync();

        logger.info("DVE Server bound to port " + port);

    } catch (Exception e) {
        throw new PEException("Failed to bind DVE server to port " + port + " - " + e.getMessage(), e);
    }
}

From source file:com.test.zp.netty.EchoClient.java

License:Apache License

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

    // 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.thomas.netty4.SimpleEchoServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    System.out.println("PORT");
    if (args.length > 0) {
        PORT = Integer.parseInt(args[0]);
    }//from   w  w  w . j  a  v  a2  s .  co m

    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {
        sslCtx = null;
    }

    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                // .option(ChannelOption.SO_BACKLOG, 100)
                .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        if (sslCtx != null) {
                            p.addLast(sslCtx.newHandler(ch.alloc()));
                        }
                        // p.addLast(new LoggingHandler(LogLevel.INFO));
                        p.addLast(new SimpleEchoServerHandler());
                    }
                });

        // Start the server.
        ChannelFuture f = b.bind(PORT).sync();

        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.titilink.camel.rest.server.CamelServer.java

License:LGPL

private static void run(int port, boolean supportSSL) {
    LOGGER.info("CamelServer run({}, {})", port, supportSSL);

    EventLoopGroup bossGroup = new NioEventLoopGroup(DEFAULT_BOSS_NIO_EVENT_NUM);
    BOSS_GROUP_LIST.add(bossGroup);/*from   w w w.  ja v  a 2 s. c  om*/
    EventLoopGroup workerGroup = new NioEventLoopGroup(DEFAULT_NIO_EVENT_NUM);
    WORKER_GROUP_LIST.add(workerGroup);

    String host = AdapterRestletUtil.getProperty(SERVER_REST_IP, LOCAL_HOST);
    HttpConnector httpConnector = new RestletConnector(host, port, supportSSL);
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new HttpServerInitializer(supportSSL, httpConnector));
        b.childOption(ChannelOption.SO_KEEPALIVE, true);
        b.childOption(ChannelOption.TCP_NODELAY, true);
        b.option(ChannelOption.SO_BACKLOG, DEFAULT_SO_BACKLOG);

        Channel ch = b.bind(new InetSocketAddress(host, port)).sync().channel();
        CHANNEL_LIST.add(ch);
        ch.closeFuture().sync();
    } catch (InterruptedException e) {
        LOGGER.error("InterruptedException while start server.");
    } catch (Throwable t) {
        LOGGER.error("CamelServer run throws error.");
    } finally {
        LOGGER.info("CamelServer run() : shutdown");
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.tongbanjie.tarzan.rpc.netty.NettyRpcClient.java

License:Apache License

@Override
public void start() {
    this.defaultEventExecutorGroup = new DefaultEventExecutorGroup(//
            nettyClientConfig.getClientWorkerThreads(), //
            new ThreadFactory() {

                private AtomicInteger threadIndex = new AtomicInteger(0);

                @Override// w w w.  j a  v a 2  s.  com
                public Thread newThread(Runnable r) {
                    return new Thread(r, "NettyClientWorkerThread_" + this.threadIndex.incrementAndGet());
                }
            });

    this.bootstrap.group(this.eventLoopGroupWorker).channel(NioSocketChannel.class)//
            //
            .option(ChannelOption.TCP_NODELAY, true)
            //
            .option(ChannelOption.SO_KEEPALIVE, false)
            //
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, nettyClientConfig.getConnectTimeoutMillis())
            //
            .option(ChannelOption.SO_SNDBUF, nettyClientConfig.getClientSocketSndBufSize())
            //
            .option(ChannelOption.SO_RCVBUF, nettyClientConfig.getClientSocketRcvBufSize())
            //
            .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 NettyConnectManageHandler(), //
                            new NettyClientHandler());
                }
            });

    this.timer.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {
            try {
                NettyRpcClient.this.scanResponseTable();
            } catch (Exception e) {
                LOGGER.error("scanResponseTable exception", e);
            }
        }
    }, 1000 * 3, 1000);

    if (this.channelEventListener != null) {
        this.nettyEventExecutor.start();
    }
}

From source file:com.tongbanjie.tarzan.rpc.netty.NettyRpcServer.java

License:Apache License

@Override
public void start() {
    this.defaultEventExecutorGroup = new DefaultEventExecutorGroup(//
            nettyServerConfig.getServerWorkerThreads(), //
            new ThreadFactory() {

                private AtomicInteger threadIndex = new AtomicInteger(0);

                @Override/* w  w w. ja  v a  2s . co m*/
                public Thread newThread(Runnable r) {
                    return new Thread(r, "NettyServerCodecThread_" + this.threadIndex.incrementAndGet());
                }
            });

    ServerBootstrap childHandler = //
            this.serverBootstrap.group(this.eventLoopGroupBoss, this.eventLoopGroupSelector)
                    .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, nettyServerConfig.getServerSocketSndBufSize())
                    //
                    .option(ChannelOption.SO_RCVBUF, nettyServerConfig.getServerSocketRcvBufSize())
                    //
                    .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 NettyConnectManageHandler(), //
                                    new NettyServerHandler());
                        }
                    });

    if (nettyServerConfig.isServerPooledByteBufAllocatorEnable()) {
        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.nettyEventExecutor.start();
    }

    this.timer.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {
            try {
                NettyRpcServer.this.scanResponseTable();
            } catch (Exception e) {
                LOGGER.error("scanResponseTable exception", e);
            }
        }
    }, 1000 * 3, 1000);

    LOGGER.info("Rpc server [port:{}] start success", port);
}

From source file:com.topsec.bdc.platform.api.test.echo.EchoClient.java

License:Apache License

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

    // Configure SSL.git
    final SslContext sslCtx;
    if (SSL) {//  w  w  w. j  a  v a 2s. com
        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();
    }
}