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.Client.NettyClient.java

License:Apache License

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

    // ?NIO//  w  w  w  .j a  va  2  s . c  o  m

    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 NettyMessageDecoder(1024 * 1024, 4, 4));
                        ch.pipeline().addLast("MessageEncoder", new NettyMessageEncoder());
                        ch.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(50));
                        ch.pipeline().addLast("LoginAuthHandler", new LoginAuthReqHandler());
                        ch.pipeline().addLast("HeartBeatHandler", new HeartBeatReqHandler());
                    }
                });
        // ??
        ChannelFuture future = b.connect(new InetSocketAddress(host, port),
                new InetSocketAddress(NettyConstant.LOCALIP, NettyConstant.LOCAL_PORT)).sync();
        future.channel().closeFuture().sync();
    } finally {
        // ????????
        executor.execute(new Runnable() {
            public void run() {
                try {
                    TimeUnit.SECONDS.sleep(1);
                    try {
                        connect(NettyConstant.PORT, NettyConstant.REMOTEIP);// ???
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

From source file:org.dcache.pool.movers.NettyTransferService.java

License:Open Source License

/**
 * Start netty server.//  w  w  w . j a va  2  s .c om
 *
 * @throws IOException Starting the server failed
 */
protected synchronized void startServer() throws IOException {
    if (serverChannel == null) {
        ServerBootstrap bootstrap = new ServerBootstrap().group(acceptGroup, socketGroup)
                .channel(NioServerSocketChannel.class).childOption(ChannelOption.TCP_NODELAY, false)
                .childOption(ChannelOption.SO_KEEPALIVE, true).childHandler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        NettyTransferService.this.initChannel(ch);
                        ChannelCdcSessionHandlerWrapper.bindSessionToChannel(ch,
                                "pool:" + address + ":" + name + ":" + ch.id());
                    }
                });

        serverChannel = portRange.bind(bootstrap);
        lastServerAddress = (InetSocketAddress) serverChannel.localAddress();
        LOGGER.debug("Started {} on {}", getClass().getSimpleName(), lastServerAddress);
    }
}

From source file:org.dcache.xrootd.standalone.DataServer.java

License:Open Source License

public void start() throws InterruptedException {
    final EventLoopGroup bossGroup;
    final EventLoopGroup workerGroup;
    Class<? extends ServerSocketChannel> channelClass;
    if (_configuration.useBlockingIo) {
        bossGroup = new OioEventLoopGroup();
        workerGroup = new OioEventLoopGroup();
        channelClass = OioServerSocketChannel.class;
    } else {//from   ww  w .  j  a va 2 s.c o m
        bossGroup = new NioEventLoopGroup();
        workerGroup = new NioEventLoopGroup();
        channelClass = NioServerSocketChannel.class;
    }
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            // Shut down all event loops to terminate all threads.
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();

            try {
                // Wait until all threads are terminated.
                bossGroup.terminationFuture().sync();
                workerGroup.terminationFuture().sync();
            } catch (InterruptedException ignored) {
            }
        }
    });
    ServerBootstrap bootstrap = new ServerBootstrap().group(bossGroup, workerGroup).channel(channelClass)
            .localAddress(_configuration.port).childOption(ChannelOption.TCP_NODELAY, true)
            .childOption(ChannelOption.SO_KEEPALIVE, true)
            .childHandler(new DataServerChannelInitializer(_configuration));

    bootstrap.bind().sync().channel().closeFuture().sync();
}

From source file:org.dcache.xrootd.tpc.XrootdTpcClient.java

License:Open Source License

public synchronized void connect(final NioEventLoopGroup group, final List<ChannelHandlerFactory> plugins,
        final TpcSourceReadHandler readHandler) throws InterruptedException {
    Bootstrap b = new Bootstrap();
    b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
            .option(ChannelOption.SO_KEEPALIVE, true).handler(new ChannelInitializer<Channel>() {
                @Override//from w  w w  .  jav a 2s  . c o m
                protected void initChannel(Channel ch) throws Exception {
                    injectHandlers(ch.pipeline(), plugins, readHandler);
                }
            });

    channelFuture = b.connect(info.getSrcHost(), info.getSrcPort()).sync();

    isRunning = true;

    notifyAll();

    sendHandshakeRequest(channelFuture.channel().pipeline().lastContext());

    LOGGER.info("Third-party client started for {}, channel {}. stream {}.", info.getSrc(),
            channelFuture.channel().id(), streamId);
}

From source file:org.ddpush.im.v1.node.pushlistener.NettyPushListener.java

License:Apache License

public void initChannel() throws Exception {
    bossGroup = new EpollEventLoopGroup();
    workerGroup = new EpollEventLoopGroup(pushListenerWorkerNum,
            new ThreadFactoryWithName(NettyPushListener.class));
    serverBootstarp = new ServerBootstrap().group(bossGroup, workerGroup)
            .channel(EpollServerSocketChannel.class).option(ChannelOption.SO_TIMEOUT, sockTimout)
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .option(ChannelOption.TCP_NODELAY, true)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.TCP_NODELAY, true).childHandler(pushListenerChannelInitializer);

    serverBootstarp.bind(port).sync();/*from w w  w  .  ja  v  a  2s.  com*/

    logger.info("Netty TCP Push Listener nio provider: {} with {} workers",
            serverBootstarp.getClass().getCanonicalName(), pushListenerWorkerNum);
}

From source file:org.didinem.client.RpcClient.java

License:Apache License

public void connect(int port, String host) throws Exception {
    // ?NIO/*from  w w w  .j  av a 2s.c  o  m*/
    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 LengthFieldBasedFrameDecoder(1024 * 1024, 0, 4, 0, 4));
                        ch.pipeline().addLast(new LengthFieldPrepender(4, false));
                        ch.pipeline().addLast(new StringDecoder());
                        ch.pipeline().addLast(new RpcClientHandler());
                    }
                });

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

    } finally {
        // NIO
        group.shutdownGracefully();
    }
}

From source file:org.diorite.impl.client.connection.ClientConnectionChannel.java

License:Open Source License

@Override
protected void initChannel(final Channel channel) throws Exception {
    try {/*from   ww w  . ja  va2s.  co  m*/
        channel.config().setOption(ChannelOption.IP_TOS, IP_TOS);
    } catch (final ChannelException ignored) {
    }
    try {
        channel.config().setOption(ChannelOption.TCP_NODELAY, false);
    } catch (final ChannelException ignored) {
    }
    channel.pipeline().addLast("timeout", new ReadTimeoutHandler(TIMEOUT_SECONDS))
            .addLast("sizer", new PacketSizer()).addLast("codec", new PacketCodec(this.clientConnection));
    final NetworkManager networkmanager = new NetworkManager(this.clientConnection.getCore());
    this.clientConnection.setConnection(networkmanager);

    channel.pipeline().addLast("packet_handler", networkmanager);
    networkmanager.setPacketListener(new HandshakeListener(this.clientConnection.getCore(), networkmanager));
}

From source file:org.diorite.impl.server.connection.ServerConnectionChannel.java

License:Open Source License

@Override
protected void initChannel(final Channel channel) throws Exception {
    try {//from  ww w  . jav a 2  s. c  o  m
        channel.config().setOption(ChannelOption.IP_TOS, IP_TOS);
    } catch (final ChannelException ignored) {
    }
    try {
        channel.config().setOption(ChannelOption.TCP_NODELAY, false);
    } catch (final ChannelException ignored) {
    }
    channel.pipeline().addLast("timeout", new ReadTimeoutHandler(TIMEOUT_SECONDS))
            .addLast("sizer", new PacketSizer()).addLast("codec", new PacketCodec(this.serverConnection)); //.addLast("legacy_query", new LegacyPingHandler(this.connectionHandler)).addLast("splitter", new PacketSplitter()).addLast("decoder", new PacketDecoder(EnumProtocolDirection.SERVERBOUND)).addLast("prepender", new PacketPrepender()).addLast("encoder", new PacketEncoder(EnumProtocolDirection.CLIENTBOUND));
    final NetworkManager networkmanager = new NetworkManager(this.serverConnection.getCore());

    this.serverConnection.getConnections().add(networkmanager);
    channel.pipeline().addLast("packet_handler", networkmanager);
    networkmanager.setPacketListener(new HandshakeListener(this.serverConnection.getCore(), networkmanager));
}

From source file:org.eclipse.milo.opcua.stack.client.UaTcpStackClient.java

License:Open Source License

public static CompletableFuture<ClientSecureChannel> bootstrap(UaTcpStackClient client,
        Optional<ClientSecureChannel> existingChannel) {

    CompletableFuture<ClientSecureChannel> handshake = new CompletableFuture<>();

    Bootstrap bootstrap = new Bootstrap();

    bootstrap.group(client.getConfig().getEventLoop()).channel(NioSocketChannel.class)
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000).option(ChannelOption.TCP_NODELAY, true)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override/*from   w w  w.j a  v  a 2 s.com*/
                protected void initChannel(SocketChannel channel) throws Exception {
                    UaTcpClientAcknowledgeHandler acknowledgeHandler = new UaTcpClientAcknowledgeHandler(client,
                            existingChannel, handshake);

                    channel.pipeline().addLast(acknowledgeHandler);
                }
            });

    try {
        URI uri = new URI(client.getEndpointUrl()).parseServerAuthority();

        bootstrap.connect(uri.getHost(), uri.getPort()).addListener((ChannelFuture f) -> {
            if (!f.isSuccess()) {
                handshake.completeExceptionally(f.cause());
            }
        });
    } catch (Throwable e) {
        UaException failure = new UaException(StatusCodes.Bad_TcpEndpointUrlInvalid, e);

        handshake.completeExceptionally(failure);
    }

    return handshake;
}

From source file:org.eclipse.milo.opcua.stack.server.transport.ServerChannelManager.java

License:Open Source License

private static CompletableFuture<Channel> bootstrap(UaStackServer stackServer, InetSocketAddress bindAddress,
        TransportProfile transportProfile) {

    ChannelInitializer<SocketChannel> initializer;

    if (transportProfile == TransportProfile.TCP_UASC_UABINARY) {
        initializer = new OpcServerTcpChannelInitializer(stackServer);
    } else {//w  w w.ja  va 2 s .  com
        initializer = new OpcServerHttpChannelInitializer(stackServer);
    }

    ServerBootstrap bootstrap = new ServerBootstrap();

    bootstrap.group(Stack.sharedEventLoop()).handler(new LoggingHandler(ServerChannelManager.class))
            .channel(NioServerSocketChannel.class)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.TCP_NODELAY, true).childHandler(initializer);

    CompletableFuture<Channel> channelFuture = new CompletableFuture<>();

    bootstrap.bind(bindAddress).addListener((ChannelFutureListener) future -> {
        if (future.isSuccess()) {
            Channel channel = future.channel();

            channelFuture.complete(channel);
        } else {
            channelFuture.completeExceptionally(future.cause());
        }
    });

    return channelFuture;
}