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:org.ireland.jnetty.JNettyServer.java

License:Apache License

public void run() throws Exception {
    // Configure the server.
    EventLoopGroup bossGroup = new AioEventLoopGroup(1);
    EventLoopGroup workerGroup = (EVENT_LOOP_THREADS == null) ? new AioEventLoopGroup()
            : new AioEventLoopGroup(EVENT_LOOP_THREADS);
    try {// w w  w.  ja  v a  2s  . c o  m
        ServerBootstrap bootstrap = new ServerBootstrap();

        bootstrap.group(bossGroup, workerGroup).channel(AioServerSocketChannel.class)
                .childHandler(new JNettySocketChannelInitializer())
                .childOption(ChannelOption.TCP_NODELAY, true);

        Channel ch = bootstrap.bind(HOST, PORT).sync().channel();
        ch.closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:org.jboss.arquillian.daemon.server.NettyServer.java

License:Apache License

/**
 * {@inheritDoc}//w  w  w  . jav a2s .  c o  m
 *
 * @see org.jboss.arquillian.daemon.server.ServerBase#startInternal()
 */
@Override
protected void startInternal() throws ServerLifecycleException, IllegalStateException {

    // Set up Netty Boostrap
    final ServerBootstrap bootstrap = new ServerBootstrap()
            .group(new NioEventLoopGroup(), new NioEventLoopGroup()).channel(NioServerSocketChannel.class)
            .localAddress(this.getBindAddress()).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(final SocketChannel channel) throws Exception {
                    final ChannelPipeline pipeline = channel.pipeline();
                    NettyServer.this.resetPipeline(pipeline);
                }
            }).childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true);
    this.bootstrap = bootstrap;

    // Start 'er up
    final ChannelFuture openChannel;
    try {
        openChannel = bootstrap.bind().sync();
    } catch (final InterruptedException ie) {
        Thread.interrupted();
        throw new ServerLifecycleException("Interrupted while awaiting server start", ie);
    } catch (final RuntimeException re) {
        // Exception xlate
        throw new ServerLifecycleException("Encountered error in binding; could not start server.", re);
    }
    // Set bound address
    final InetSocketAddress boundAddress = ((InetSocketAddress) openChannel.channel().localAddress());
    this.setBoundAddress(boundAddress);
}

From source file:org.jfxvnc.net.SampleVncClient.java

License:Apache License

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

    ProtocolConfiguration config = new DefaultProtocolConfiguration();

    if (args != null && args.length >= 3) {
        config.securityProperty().set(SecurityType.VNC_Auth);
        config.hostProperty().set(args[0]);
        config.portProperty().set(Integer.parseInt(args[1]));
        config.passwordProperty().set(args[2]);
        config.sharedProperty().set(Boolean.TRUE);
    } else {/*from ww w .  j a v a 2 s .  c om*/
        System.err.println("arguments missing (host port password)");
        config.securityProperty().set(SecurityType.VNC_Auth);
        config.hostProperty().set("127.0.0.1");
        config.portProperty().set(5902);
        config.passwordProperty().set("vnc");
        config.sharedProperty().set(Boolean.TRUE);
    }

    String host = config.hostProperty().get();
    int port = config.portProperty().get();

    // final SslContext sslContext =
    // SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);

    EventLoopGroup workerGroup = new NioEventLoopGroup(1);
    try {
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.option(ChannelOption.TCP_NODELAY, true);

        b.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {

                // use ssl
                // ch.pipeline().addLast(sslContext.newHandler(ch.alloc()));
                ch.pipeline().addLast(new ProtocolHandler(new RenderProtocol() {

                    @Override
                    public void render(ImageRect rect, RenderCallback callback) {
                        System.out.println(rect);
                        callback.renderComplete();
                    }

                    @Override
                    public void exceptionCaught(Throwable t) {
                        t.printStackTrace();
                    }

                    @Override
                    public void stateChanged(ProtocolState state) {
                        System.out.println(state);
                    }

                    @Override
                    public void registerInputEventListener(InputEventListener listener) {
                    }

                    @Override
                    public void eventReceived(ServerDecoderEvent evnt) {
                        System.out.println(evnt);
                    }

                }, config));
            }
        });

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

        f.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
    }
}

From source file:org.jfxvnc.ui.service.VncRenderService.java

License:Apache License

private boolean connect() throws Exception {
    connectProperty.set(true);/*  ww  w.  j a  v a2  s . co  m*/
    shutdown();
    workerGroup = new NioEventLoopGroup();

    String host = config.hostProperty().get();
    int port = config.portProperty().get() > 0 ? config.portProperty().get() : CONNECT_PORT;

    Bootstrap b = new Bootstrap();
    b.group(workerGroup);
    b.channel(NioSocketChannel.class);
    b.option(ChannelOption.SO_KEEPALIVE, true);
    b.option(ChannelOption.TCP_NODELAY, true);
    b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000);

    b.handler(new ProtocolInitializer(VncRenderService.this, config));

    logger.info("try to connect to {}:{}", host, port);
    ChannelFuture f = b.connect(host, port);
    f.await(5000);

    connectProperty.set(f.isSuccess());
    logger.info("connection {}", connectProperty.get() ? "established" : "failed");
    if (f.isCancelled()) {
        logger.warn("connection aborted");
    } else if (!f.isSuccess()) {
        logger.error("connection failed", f.cause());
        exceptionCaughtProperty.set(f.cause() != null ? f.cause()
                : new Exception("connection failed to host: " + host + ":" + port));
    }
    return connectProperty.get();
}

From source file:org.jmqtt.broker.acceptor.NettyAcceptor.java

License:Open Source License

private void initFactory(String host, int port, final PipelineInitializer pipeliner) {
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override//from   w  ww  . ja v a2 s .  c o m
                public void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    try {
                        pipeliner.init(pipeline);
                    } catch (Throwable th) {
                        LOG.error("Severe error during pipeline creation", th);
                        throw th;
                    }
                }
            }).option(ChannelOption.SO_BACKLOG, 128).option(ChannelOption.SO_REUSEADDR, true)
            .option(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true);
    try {
        // Bind and start to accept incoming connections.
        ChannelFuture f = b.bind(host, port);
        LOG.info("Server binded host: {}, port: {}", host, port);
        f.sync();
    } catch (InterruptedException ex) {
        LOG.error(null, ex);
    }
}

From source file:org.jupiter.transport.netty.NettyTcpAcceptor.java

License:Apache License

@Override
protected void setOptions() {
    super.setOptions();

    ServerBootstrap boot = bootstrap();//from   ww w  .  j  a v  a2  s. c  o  m

    // parent options
    NettyConfig.NettyTcpConfigGroup.ParentConfig parent = configGroup.parent();
    boot.option(ChannelOption.SO_BACKLOG, parent.getBacklog());
    boot.option(ChannelOption.SO_REUSEADDR, parent.isReuseAddress());
    if (parent.getRcvBuf() > 0) {
        boot.option(ChannelOption.SO_RCVBUF, parent.getRcvBuf());
    }

    // child options
    NettyConfig.NettyTcpConfigGroup.ChildConfig child = configGroup.child();
    boot.childOption(ChannelOption.SO_REUSEADDR, child.isReuseAddress())
            .childOption(ChannelOption.SO_KEEPALIVE, child.isKeepAlive())
            .childOption(ChannelOption.TCP_NODELAY, child.isTcpNoDelay())
            .childOption(ChannelOption.ALLOW_HALF_CLOSURE, child.isAllowHalfClosure());
    if (child.getRcvBuf() > 0) {
        boot.childOption(ChannelOption.SO_RCVBUF, child.getRcvBuf());
    }
    if (child.getSndBuf() > 0) {
        boot.childOption(ChannelOption.SO_SNDBUF, child.getSndBuf());
    }
    if (child.getLinger() > 0) {
        boot.childOption(ChannelOption.SO_LINGER, child.getLinger());
    }
    if (child.getIpTos() > 0) {
        boot.childOption(ChannelOption.IP_TOS, child.getIpTos());
    }
    int bufLowWaterMark = child.getWriteBufferLowWaterMark();
    int bufHighWaterMark = child.getWriteBufferHighWaterMark();
    if (bufLowWaterMark >= 0 && bufHighWaterMark > 0) {
        WriteBufferWaterMark waterMark = new WriteBufferWaterMark(bufLowWaterMark, bufHighWaterMark);
        boot.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK, waterMark);
    }
}

From source file:org.jupiter.transport.netty.NettyTcpConnector.java

License:Apache License

@Override
protected void setOptions() {
    super.setOptions();

    Bootstrap boot = bootstrap();/*from   w  w  w  .  j a v  a2  s  .  c  o  m*/

    NettyConfig.NettyTcpConfigGroup.ChildConfig child = childConfig;

    // child options
    boot.option(ChannelOption.SO_REUSEADDR, child.isReuseAddress())
            .option(ChannelOption.SO_KEEPALIVE, child.isKeepAlive())
            .option(ChannelOption.TCP_NODELAY, child.isTcpNoDelay())
            .option(ChannelOption.ALLOW_HALF_CLOSURE, child.isAllowHalfClosure());
    if (child.getRcvBuf() > 0) {
        boot.option(ChannelOption.SO_RCVBUF, child.getRcvBuf());
    }
    if (child.getSndBuf() > 0) {
        boot.option(ChannelOption.SO_SNDBUF, child.getSndBuf());
    }
    if (child.getLinger() > 0) {
        boot.option(ChannelOption.SO_LINGER, child.getLinger());
    }
    if (child.getIpTos() > 0) {
        boot.option(ChannelOption.IP_TOS, child.getIpTos());
    }
    if (child.getConnectTimeoutMillis() > 0) {
        boot.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, child.getConnectTimeoutMillis());
    }
    int bufLowWaterMark = child.getWriteBufferLowWaterMark();
    int bufHighWaterMark = child.getWriteBufferHighWaterMark();
    if (bufLowWaterMark >= 0 && bufHighWaterMark > 0) {
        WriteBufferWaterMark waterMark = new WriteBufferWaterMark(bufLowWaterMark, bufHighWaterMark);
        boot.option(ChannelOption.WRITE_BUFFER_WATER_MARK, waterMark);
    }
}

From source file:org.kaazing.messaging.driver.transport.netty.tcp.NettyTransportContext.java

License:Apache License

public NettyTransportContext() {
    super();/*from  www  . ja  va2  s .  c  o m*/

    if (USE_SSL) {
        SelfSignedCertificate ssc = null;
        try {
            ssc = new SelfSignedCertificate();
            serverSslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
            clientSslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE)
                    .build();
        } catch (CertificateException e) {
            LOGGER.error("CertificateException", e);
            throw new IllegalArgumentException("Error creating transport context", e);
        } catch (SSLException e) {
            LOGGER.error("SSLException", e);
            throw new IllegalArgumentException("Error creating transport context", e);
        }
    } else {
        serverSslCtx = null;
        clientSslCtx = null;
    }

    // Configure the server.
    serverBossGroup = new NioEventLoopGroup(1);
    serverWorkerGroup = new NioEventLoopGroup();

    serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(serverBossGroup, serverWorkerGroup).channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_BACKLOG, 100).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    final ChannelPipeline p = ch.pipeline();
                    if (serverSslCtx != null) {
                        p.addLast(serverSslCtx.newHandler(ch.alloc()));
                    }
                    p.addLast(new LengthFieldBasedFrameDecoder(1000000, 0, 4, 0, 4));
                    serverReceivingTransportsLock.readLock().lock();
                    try {
                        serverReceivingTransports.forEach((nettyReceivingTransport) -> {
                            if (ch.localAddress().equals(nettyReceivingTransport.getInetSocketAddress())
                                    || nettyReceivingTransport.isInAddrAny()
                                            && ch.localAddress().getPort() == nettyReceivingTransport
                                                    .getInetSocketAddress().getPort()) {
                                p.addLast(nettyReceivingTransport.getNettyChannelHandler());
                            }
                        });
                    } finally {
                        serverReceivingTransportsLock.readLock().unlock();
                    }

                }
            });

    bootstrap = new Bootstrap();
    group = new NioEventLoopGroup();
    bootstrap.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 (clientSslCtx != null) {
                        p.addLast(clientSslCtx.newHandler(ch.alloc()));
                    }
                }
            });
}

From source file:org.kayla.Server.java

License:Open Source License

public static void main(String[] agrs) {
    try {/* w  w  w.  j av  a  2  s. c om*/
        cache = new Cache(FileStore.open(Constants.CACHE_REPOSITORY));
        table = cache.createChecksumTable().encode();

        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {

                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new GameChannelHandler());
                    }

                }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.TCP_NODELAY, true);

        try {
            future = bootstrap.bind(43594).sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        logger.info("Bound " + Constants.FRAME_NAME + " on: " + future.channel().localAddress().toString());

    } catch (IOException e) {
        logger.error("Error starting " + Constants.FRAME_NAME + "!", e);
    }
}

From source file:org.kitteh.irc.client.library.implementation.NettyManager.java

License:Open Source License

static synchronized ClientConnection connect(@Nonnull InternalClient client) {
    if (bootstrap == null) {
        bootstrap = new Bootstrap();
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override/*from ww w  .  ja v a2 s.  c  om*/
            public void initChannel(SocketChannel channel) throws Exception {
                // NOOP
            }
        });
        bootstrap.option(ChannelOption.TCP_NODELAY, true);
        eventLoopGroup = new NioEventLoopGroup();
        bootstrap.group(eventLoopGroup);
    }
    SocketAddress bind = client.getConfig().get(Config.BIND_ADDRESS);
    SocketAddress server = client.getConfig().getNotNull(Config.SERVER_ADDRESS);
    ClientConnection clientConnection;
    if (bind == null) {
        clientConnection = new ClientConnection(client, bootstrap.connect(server));
    } else {
        clientConnection = new ClientConnection(client, bootstrap.connect(server, bind));
    }
    connections.add(clientConnection);
    return clientConnection;
}