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.piindustries.pinetwork.client.Client.java

License:Apache License

public void run() throws Exception {
    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {//w ww.  ja  va 2  s . com
        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 LoggingHandler(LogLevel.INFO),
                                new ClientHandler(firstMessageSize));
                    }
                });

        // 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:org.poweredrails.rails.net.NetworkManager.java

License:MIT License

public NetworkManager(Logger logger) {
    this.logger = logger;

    PacketRegistry packetRegistry = new PacketRegistry();
    HandlerRegistry handlerRegistry = new HandlerRegistry();
    SessionManager sessionManager = new SessionManager();
    this.nettyBootstrap.group(this.nettyBossGroup, this.nettyWorkerGroup).channel(NioServerSocketChannel.class)
            .childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true)
            .childHandler(// w  w w  .ja  va 2 s  . c  o  m
                    new ServerChannelInitializer(this.logger, sessionManager, packetRegistry, handlerRegistry));
}

From source file:org.ratpackframework.bootstrap.internal.NettyRatpackService.java

License:Apache License

@Override
protected void startUp() throws Exception {
    ServerBootstrap bootstrap = new ServerBootstrap();
    group = new NioEventLoopGroup(MultithreadEventLoopGroup.DEFAULT_EVENT_LOOP_THREADS,
            new DefaultThreadFactory("ratpack-group", Thread.MAX_PRIORITY));

    bootstrap.group(group).channel(NioServerSocketChannel.class).childHandler(channelInitializer);

    bootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    bootstrap.childOption(ChannelOption.TCP_NODELAY, true);
    bootstrap.option(ChannelOption.SO_REUSEADDR, true);
    bootstrap.option(ChannelOption.SO_BACKLOG, 1024);

    channel = bootstrap.bind(requestedAddress).sync().channel();
    boundAddress = (InetSocketAddress) channel.localAddress();

    if (logger.isLoggable(Level.INFO)) {
        logger.info(String.format("Ratpack started for http://%s:%s", getBindHost(), getBindPort()));
    }// w  w  w .  j  a va 2 s  . com
}

From source file:org.ratpackframework.server.internal.NettyRatpackService.java

License:Apache License

@Override
protected void startUp() throws Exception {
    ServerBootstrap bootstrap = new ServerBootstrap();
    group = new NioEventLoopGroup(launchConfig.getMainThreads(),
            new DefaultThreadFactory("ratpack-group", Thread.MAX_PRIORITY));

    bootstrap.group(group).channel(NioServerSocketChannel.class).childHandler(channelInitializer)
            .childOption(ChannelOption.ALLOCATOR, launchConfig.getBufferAllocator())
            .childOption(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_REUSEADDR, true)
            .option(ChannelOption.SO_BACKLOG, 1024)
            .option(ChannelOption.ALLOCATOR, launchConfig.getBufferAllocator());

    try {//w  w  w  . j  ava2 s  .co  m
        channel = bootstrap.bind(buildSocketAddress()).sync().channel();
    } catch (Exception e) {
        partialShutdown();
        throw e;
    }
    boundAddress = (InetSocketAddress) channel.localAddress();

    if (logger.isLoggable(Level.INFO)) {
        logger.info(String.format("Ratpack started for http://%s:%s", getBindHost(), getBindPort()));
    }
}

From source file:org.robotninjas.protobuf.netty.client.RpcClient.java

License:Open Source License

<T extends SocketChannel> RpcClient(EventLoopGroup eventLoopGroup, Optional<EventExecutorGroup> eventExecutor,
        Class<T> channel) {
    bootstrap.group(eventLoopGroup);//from w  w  w .ja  v  a 2  s.  co m
    bootstrap.channel(channel);
    if (eventExecutor.isPresent()) {
        bootstrap.handler(new ClientInitializer<T>(eventExecutor.get()));
    } else {
        bootstrap.handler(new ClientInitializer<T>());
    }
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
}

From source file:org.robotninjas.protobuf.netty.server.RpcServer.java

License:Open Source License

<T extends ServerSocketChannel> RpcServer(EventLoopGroup eventLoopGroup,
        Optional<EventExecutorGroup> eventExecutor, Class<T> channel, SocketAddress address) {
    this.address = address;
    this.allChannels = new DefaultChannelGroup(eventLoopGroup.next());
    this.handler = new ServerHandler(allChannels);
    this.bootstrap = new ServerBootstrap();
    bootstrap.channel(channel);//from  w w  w .  ja v  a 2 s .c  o m
    if (eventExecutor.isPresent()) {
        bootstrap.childHandler(new ServerInitializer(eventExecutor.get(), handler));
    } else {
        bootstrap.childHandler(new ServerInitializer(handler));
    }
    bootstrap.group(eventLoopGroup);
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
}

From source file:org.rzo.netty.ahessian.bootstrap.DefaultServer.java

License:Apache License

private void setChannelOptions(Set<String> channelOptions) {
    if (channelOptions == null)
        return;/*from   www  . j  a v a  2  s .  co  m*/
    // TODO add more options
    if (channelOptions.contains("IPTOS_THROUGHPUT"))
        bootstrap.childOption(ChannelOption.IP_TOS, IPTOS_THROUGHPUT);
    else if (channelOptions.contains("IPTOS_LOWDELAY"))
        bootstrap.childOption(ChannelOption.IP_TOS, IPTOS_LOWDELAY);
    else if (channelOptions.contains("TCP_NODELAY"))
        bootstrap.childOption(ChannelOption.TCP_NODELAY, true);
    else if (channelOptions.contains("SO_REUSE"))
        bootstrap.childOption(ChannelOption.SO_REUSEADDR, true);

}

From source file:org.rzo.yajsw.app.WrapperManagerImpl.java

License:Apache License

public void start() {
    try {// w  w  w .  jav a 2s  .c om
        // hack: avoid netty hangs on connect
        if (_config.getBoolean("wrapper.console.pipestreams", false)) {
            Socket dummy = new Socket("127.0.0.1", _port);
            OutputStream out = dummy.getOutputStream();
            out.close();
            dummy.close();
        }
    } catch (Throwable e1) {
        if (_debug > 1)
            e1.printStackTrace();
    }

    connector = new Bootstrap();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    // workerGroup.setIoRatio(99);
    connector.group(workerGroup);
    connector.channel(NioSocketChannel.class);

    connector.remoteAddress(new InetSocketAddress("127.0.0.1", _port));
    connector.option(ChannelOption.SO_REUSEADDR, true);
    connector.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10 * 1000);
    connector.option(ChannelOption.TCP_NODELAY, true);

    if (_debugComm)
        connector.handler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline()
                        .addLast(new io.netty.channel.ChannelHandler[] {
                                new SystemOutLoggingFilter("WrapperManager"),
                                new DelimiterBasedFrameDecoder(8192, true, Delimiters.nulDelimiter()),
                                new MessageEncoder(), new MessageDecoder(), new WrapperHandler() }

                );
            }

        });
    else
        connector.handler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline()
                        .addLast(new io.netty.channel.ChannelHandler[] {
                                new DelimiterBasedFrameDecoder(8192, true, Delimiters.nulDelimiter()),
                                new MessageEncoder(), new MessageDecoder(), new WrapperHandler() }

                );
            }

        });

    // pinger is a cycler with high priority threads
    // sends ping messages within a ping interval
    _pinger = new Cycler(getPingInterval(), 0,
            Executors.newCachedThreadPool(new DaemonThreadFactory("pinger", Thread.MAX_PRIORITY)),
            new Runnable() {
                long start = System.currentTimeMillis();

                public void run() {
                    ChannelFuture future;
                    if (_session != null && _session.isActive() && !_stopping && !_appearHanging) {
                        synchronized (_heapDataLock) {
                            if (_sendHeapData) {
                                if (minorGCDuration == -1)
                                    getGCData();
                                future = _session.writeAndFlush(
                                        new Message(Constants.WRAPPER_MSG_PING, "" + currentPercentHeap + ";"
                                                + minorGCDuration + ";" + fullGCDuration + ";" + lastUsedHeap));
                                currentPercentHeap = -1;
                                minorGCDuration = -1;
                                fullGCDuration = -1;
                            } else {
                                future = _session.writeAndFlush(new Message(Constants.WRAPPER_MSG_PING, ""));
                            }
                        }
                        try {
                            future.await(10000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        start = System.currentTimeMillis();
                    } else if ((_haltAppOnWrapper && (System.currentTimeMillis() - start) > _startupTimeout)
                            && !_stopping) {
                        System.out.println("no connection to wrapper during " + (_startupTimeout / 1000)
                                + " seconds -> System.exit(-1)");
                        System.out.println(
                                "if this is due to server overload consider increasing yajsw configuration property wrapper.startup.timeout");
                        System.exit(-1);
                    }
                }
            });
    _pinger.start();

    // connect
    // handler should process messages in a separate thread

    reconnect();
    /*
     * try { if (_config.getInt("wrapper.action.port") > 0) { _actionHandler
     * = new ActionHandler(this, _config); _actionHandler.start(); } } catch
     * (Exception ex) { log.info("could not start action handler " +
     * ex.getMessage()); }
     */

}

From source file:org.rzo.yajsw.controller.jvm.JVMController.java

License:Apache License

/**
 * Instantiates a new controller.//from ww  w.ja  v  a  2s  .  com
 * 
 * @param wrappedJavaProcess
 *            the wrapped java process
 */
public JVMController(WrappedProcess wrappedJavaProcess) {
    super(wrappedJavaProcess);
    _bossGroup = new OioEventLoopGroup();
    _workerGroup = new OioEventLoopGroup();
    ControllerPipelineFactory pipelineFactory = new ControllerPipelineFactory(this);

    pipelineFactory.setDebug(_debug > 2);
    _acceptor = new ServerBootstrap().group(_bossGroup, _workerGroup).channel(OioServerSocketChannel.class)
            .childOption(ChannelOption.TCP_NODELAY, true)
            // .option(ChannelOption.SO_BACKLOG, 128)
            .childHandler(pipelineFactory);

}

From source file:org.scache.network.client.TransportClientFactory.java

License:Apache License

/** Create a completely new {@link TransportClient} to the remote address. */
private TransportClient createClient(InetSocketAddress address) throws IOException {
    logger.debug("Creating new connection to " + address);

    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(workerGroup).channel(socketChannelClass)
            // Disable Nagle's Algorithm since we don't want packets to wait
            .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, conf.connectionTimeoutMs())
            .option(ChannelOption.ALLOCATOR, pooledAllocator);

    final AtomicReference<TransportClient> clientRef = new AtomicReference<>();
    final AtomicReference<Channel> channelRef = new AtomicReference<>();

    bootstrap.handler(new ChannelInitializer<SocketChannel>() {
        @Override//from w  w  w  .  j a  va2  s  . c  om
        public void initChannel(SocketChannel ch) {
            TransportChannelHandler clientHandler = context.initializePipeline(ch);
            clientRef.set(clientHandler.getClient());
            channelRef.set(ch);
        }
    });

    // Connect to the remote server
    long preConnect = System.nanoTime();
    ChannelFuture cf = bootstrap.connect(address);
    if (!cf.awaitUninterruptibly(conf.connectionTimeoutMs())) {
        throw new IOException(
                String.format("Connecting to %s timed out (%s ms)", address, conf.connectionTimeoutMs()));
    } else if (cf.cause() != null) {
        throw new IOException(String.format("Failed to connect to %s", address), cf.cause());
    }

    TransportClient client = clientRef.get();
    Channel channel = channelRef.get();
    assert client != null : "Channel future completed successfully with null client";

    // Execute any client bootstraps synchronously before marking the Client as successful.
    long preBootstrap = System.nanoTime();
    logger.debug("Connection to {} successful, running bootstraps...", address);
    try {
        for (TransportClientBootstrap clientBootstrap : clientBootstraps) {
            clientBootstrap.doBootstrap(client, channel);
        }
    } catch (Exception e) { // catch non-RuntimeExceptions too as bootstrap may be written in Scala
        long bootstrapTimeMs = (System.nanoTime() - preBootstrap) / 1000000;
        logger.error("Exception while bootstrapping client after " + bootstrapTimeMs + " ms", e);
        client.close();
        throw Throwables.propagate(e);
    }
    long postBootstrap = System.nanoTime();

    logger.info("Successfully created connection to {} after {} ms ({} ms spent in bootstraps)", address,
            (postBootstrap - preConnect) / 1000000, (postBootstrap - preBootstrap) / 1000000);

    return client;
}