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:fixio.FixClient.java

License:Apache License

public ChannelFuture connect(SocketAddress serverAddress) throws InterruptedException {
    Bootstrap b = new Bootstrap();
    bossEventLoopGroup = new NioEventLoopGroup();
    workerEventLoopGroup = new NioEventLoopGroup(8);
    b.group(bossEventLoopGroup).channel(NioSocketChannel.class).remoteAddress(serverAddress)
            .option(ChannelOption.TCP_NODELAY,
                    Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.nodelay", "true")))
            .option(ChannelOption.ALLOCATOR, new PooledByteBufAllocator())
            .handler(new FixInitiatorChannelInitializer<SocketChannel>(workerEventLoopGroup,
                    sessionSettingsProvider, messageSequenceProvider, getFixApplication()))
            .validate();/*from w  w w .  ja  v a 2 s  .  com*/

    channel = b.connect().sync().channel();
    LOGGER.info("FixClient is started and connected to {}", channel.remoteAddress());
    return channel.closeFuture();
}

From source file:fixio.FixServer.java

License:Apache License

public void start() throws InterruptedException {
    bossGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup(8);
    final ServerBootstrap bootstrap = new ServerBootstrap();
    final FixAcceptorChannelInitializer<SocketChannel> channelInitializer = new FixAcceptorChannelInitializer<>(
            workerGroup, authenticator, getFixApplication());

    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childOption(ChannelOption.TCP_NODELAY,
                    Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.nodelay", "true")))
            .childOption(ChannelOption.ALLOCATOR, new PooledByteBufAllocator())
            .localAddress(new InetSocketAddress(port)).childHandler(channelInitializer).validate();

    ChannelFuture f = bootstrap.bind().sync();
    LOGGER.info("FixServer is started at {}", f.channel().localAddress());
    channel = f.channel();//from   ww  w.j av  a  2s.com
}

From source file:fr.kissy.zergling_push.MainServer.java

License:Apache License

private void run() throws Exception {
    final ChannelGroup allPlayers = new DefaultChannelGroup("AllPlayers", GlobalEventExecutor.INSTANCE);
    final ArrayBlockingQueue<PlayerMessage> messagesQueue = new ArrayBlockingQueue<PlayerMessage>(1024);

    final World world = new World();
    final MainLoop mainLoop = new MainLoop(world, allPlayers, messagesQueue);

    ScheduledThreadPoolExecutor mainLoopExecutor = new ScheduledThreadPoolExecutor(1);
    mainLoopExecutor.scheduleAtFixedRate(mainLoop, 0, TICK_RATE, TimeUnit.MILLISECONDS);

    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    EventExecutorGroup executorGroup = new DefaultEventExecutorGroup(16);

    try {/*from  w  w  w . j  ava 2 s. c o  m*/
        final ServerBootstrap sb = new ServerBootstrap();
        sb.childOption(ChannelOption.TCP_NODELAY, true);
        sb.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(final SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast("http-decoder", new HttpServerCodec());
                        pipeline.addLast("http-aggregator", new HttpObjectAggregator(65536));
                        pipeline.addLast("websocket-compression", new WebSocketServerCompressionHandler());
                        pipeline.addLast("websocket-protocol",
                                new WebSocketServerProtocolHandler(WEBSOCKET_PATH, null, true));
                        pipeline.addLast(executorGroup, "flatbuffer-message",
                                new FlatBufferMessageHandler(world, messagesQueue));
                        pipeline.addLast("http-server", new HttpStaticFileServerHandler());
                    }
                }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);
        final Channel ch = sb.bind(8080).sync().channel();
        ch.closeFuture().sync();
    } catch (Exception e) {
        throw new RuntimeException("Error while running server", e);
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:fr.letroll.ttorrentandroid.client.io.PeerClient.java

License:Apache License

public void start() throws Exception {
    group = new NioEventLoopGroup();
    bootstrap = new Bootstrap();
    bootstrap.group(group);/*from  w w w . ja v  a  2s. c o m*/
    bootstrap.channel(NioSocketChannel.class);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.option(ChannelOption.SO_REUSEADDR, true);
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    // bootstrap.option(ChannelOption.SO_TIMEOUT, (int) TimeUnit.MINUTES.toMillis(CLIENT_KEEP_ALIVE_MINUTES));
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) TimeUnit.SECONDS.toMillis(10));
    // bootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, (int) TimeUnit.SECONDS.toMillis(10));
}

From source file:fr.letroll.ttorrentandroid.client.io.PeerServer.java

License:Apache License

public void start() throws Exception {
    group = new NioEventLoopGroup();
    ServerBootstrap b = new ServerBootstrap();
    b.group(group);/* w  w  w.  jav  a2 s.  c  om*/
    b.channel(NioServerSocketChannel.class);
    b.option(ChannelOption.SO_BACKLOG, 128);
    b.option(ChannelOption.SO_REUSEADDR, true);
    b.option(ChannelOption.TCP_NODELAY, true);
    b.childHandler(new PeerServerHandshakeHandler(client));
    b.childOption(ChannelOption.SO_KEEPALIVE, true);
    // b.childOption(ChannelOption.SO_TIMEOUT, (int) TimeUnit.MINUTES.toMillis(CLIENT_KEEP_ALIVE_MINUTES));
    if (address != null) {
        future = b.bind(address).sync();
    } else {
        BIND: {
            Exception x = new IOException("No available port for the BitTorrent client!");
            for (int i = PORT_RANGE_START; i <= PORT_RANGE_END; i++) {
                try {
                    future = b.bind(i).sync();
                    break BIND;
                } catch (InterruptedException e) {
                    throw e;
                } catch (Exception e) {
                    x = e;
                }
            }
            throw new IOException("Failed to find an address to bind in range [" + PORT_RANGE_START + ","
                    + PORT_RANGE_END + "]", x);
        }
    }
}

From source file:gash.router.client.CommConnection.java

License:Apache License

private void init() {
    System.out.println("--> initializing connection to " + host + ":" + port);
    // the queue to support client-side surging
    outbound = new LinkedBlockingDeque<CommandMessage>();
    group = new NioEventLoopGroup();
    try {//from  ww  w .  ja  v a 2  s .c  o  m
        CommInit si = new CommInit(false);
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(si);
        b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);
        b.option(ChannelOption.TCP_NODELAY, true);
        b.option(ChannelOption.SO_KEEPALIVE, true);

        // Make the connection attempt.
        channel = b.connect(host, port).syncUninterruptibly();

        System.out.println("Printing channel " + channel);

        // want to monitor the connection to the server s.t. if we loose the
        // connection, we can try to re-establish it.
        ClientClosedListener ccl = new ClientClosedListener(this);
        channel.channel().closeFuture().addListener(ccl);
        System.out.println(channel.channel().localAddress() + " -> open: " + channel.channel().isOpen()
                + ", write: " + channel.channel().isWritable() + ", reg: " + channel.channel().isRegistered());
    } catch (Throwable ex) {
        logger.error("failed to initialize the client connection", ex);
        ex.printStackTrace();
    }

    // start outbound message processor
    worker = new CommWorker(this);
    worker.setDaemon(true);
    worker.start();
}

From source file:gash.router.global.edges.GlobalEdgeMonitor.java

License:Apache License

private Channel connectToChannel(String host, int port) {
    Bootstrap b = new Bootstrap();
    NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup();
    GlobalInit globalInit = new GlobalInit(server, false);

    try {// ww  w  . ja  v a  2s  . c o m
        b.group(nioEventLoopGroup).channel(NioSocketChannel.class).handler(globalInit);
        b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);
        b.option(ChannelOption.TCP_NODELAY, true);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        // Make the connection attempt.
    } catch (Exception e) {
        logger.error("Could not connect to the host " + host);
        return null;
    }
    return b.connect(host, port).syncUninterruptibly().channel();

}

From source file:gash.router.server.communication.CommConnection.java

License:Apache License

/**
 * abstraction of notification in the communication
 * /*  w  w  w  . j  a  va  2 s. c o  m*/
 * @param listener
 */
/*public void addListener(CommListener listener) {
   CommHandler handler = connect().pipeline().get(CommHandler.class);
   if (handler != null)
 handler.addListener(listener);
}*/

private void init() {
    System.out.println("--> initializing connection to " + host + ":" + port);

    // the queue to support client-side surging
    //outbound = new LinkedBlockingDeque<CommandMessage>();

    group = new NioEventLoopGroup();
    try {
        CommInit si = new CommInit(false);
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(si);
        b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 100000);
        b.option(ChannelOption.TCP_NODELAY, true);
        b.option(ChannelOption.SO_KEEPALIVE, true);

        // Make the connection attempt.
        channel = b.connect(host, port).syncUninterruptibly();

        // want to monitor the connection to the server s.t. if we loose the
        // connection, we can try to re-establish it.
        ClientClosedListener ccl = new ClientClosedListener(this);
        channel.channel().closeFuture().addListener(ccl);

        System.out.println(channel.channel().localAddress() + " -> open: " + channel.channel().isOpen()
                + ", write: " + channel.channel().isWritable() + ", reg: " + channel.channel().isRegistered());

    } catch (Throwable ex) {
        logger.error("failed to initialize the client connection");//, ex);
        //ex.printStackTrace();
    }

    // start outbound message processor
    //worker = new CommWorker(this);
    //worker.setDaemon(true);
    //worker.start();
}

From source file:gash.router.server.edges.EdgeMonitor.java

License:Apache License

private Channel connectToChannel(String host, int port) {
    Bootstrap b = new Bootstrap();
    NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup();
    WorkInit workInit = new WorkInit(state, false);

    try {/*w w w  . j a  v a 2  s  .  c o  m*/
        b.group(nioEventLoopGroup).channel(NioSocketChannel.class).handler(workInit);
        b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);
        b.option(ChannelOption.TCP_NODELAY, true);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        // Make the connection attempt.
    } catch (Exception e) {
        logger.error("Could not connect to the host " + host);
        return null;
    }
    return b.connect(host, port).syncUninterruptibly().channel();

}

From source file:github.com.cp149.netty.server.NettyappenderServer.java

License:Apache License

public void run() throws Exception {

    try {//  w w w  .  j a  va 2  s  .c  om
        bootstrap = new ServerBootstrap();
        final EventExecutorGroup executor = new DefaultEventExecutorGroup(4);

        bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childOption(ChannelOption.SO_KEEPALIVE, true).childOption(ChannelOption.TCP_NODELAY, true)
                .childOption(ChannelOption.SO_RCVBUF, 65535).childOption(ChannelOption.SO_SNDBUF, 2048)
                .childOption(ChannelOption.SO_REUSEADDR, true) //reuse address
                .childOption(ChannelOption.ALLOCATOR, new PooledByteBufAllocator(false))// heap buf 's better               
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        //                     ch.pipeline().addLast( new MarshallingEncoder(MarshallUtil.createProvider()));
                        //                     ch.pipeline().addLast(new CompatibleObjectDecoder());
                        //                     ch.pipeline().addLast(new ObjectEncoder(),
                        //                                  new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
                        ch.pipeline().addLast(new MarshallingDecoder(MarshallUtil.createUnProvider()));

                        ch.pipeline().addLast(executor, new NettyappenderServerHandler());
                        //
                    }
                });

        bootstrap.bind(port).sync();

    } finally {

    }
    // bootstrap = new ServerBootstrap(new
    // NioServerSocketChannelFactory(Executors.newFixedThreadPool(4),
    // Executors.newFixedThreadPool(4)));
    // final ExecutionHandler executionHandler = new ExecutionHandler(new
    // OrderedMemoryAwareThreadPoolExecutor(4, 1024 * 1024 * 300, 1024 *
    // 1024 * 300 * 2));
    // bootstrap.setOption("tcpNoDelay", true);
    // bootstrap.setOption("keepAlive", true);
    // // bootstrap.setOption("writeBufferHighWaterMark", 100 * 64 * 1024);
    // // bootstrap.setOption("sendBufferSize", 1048576);
    // bootstrap.setOption("receiveBufferSize", 1048576*10 );
    //
    // // Set up the pipeline factory.
    // bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
    // public ChannelPipeline getPipeline() throws Exception {
    // return Channels.pipeline(executionHandler, new
    // MarshallingDecoder(createProvider(createMarshallerFactory(),
    // createMarshallingConfig())),
    // new NettyappenderServerHandler());
    // }
    // });

    // // Bind and start to accept incoming connections.
    // bootstrap.bind(new InetSocketAddress(port));
    //       LoggerFactory.getLogger(this.getClass()).info("start server at" +
    //             port);
}