Example usage for io.netty.channel ChannelOption SO_KEEPALIVE

List of usage examples for io.netty.channel ChannelOption SO_KEEPALIVE

Introduction

In this page you can find the example usage for io.netty.channel ChannelOption SO_KEEPALIVE.

Prototype

ChannelOption SO_KEEPALIVE

To view the source code for io.netty.channel ChannelOption SO_KEEPALIVE.

Click Source Link

Usage

From source file:com.look.netty.demo.socksproxy.SocksServerConnectHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksMessage message) throws Exception {
    if (message instanceof Socks4CommandRequest) {
        final Socks4CommandRequest request = (Socks4CommandRequest) message;
        Promise<Channel> promise = ctx.executor().newPromise();
        promise.addListener(new FutureListener<Channel>() {
            @Override/* w ww .  j a va2  s .c  o  m*/
            public void operationComplete(final Future<Channel> future) throws Exception {
                final Channel outboundChannel = future.getNow();
                if (future.isSuccess()) {
                    ChannelFuture responseFuture = ctx.channel()
                            .writeAndFlush(new DefaultSocks4CommandResponse(Socks4CommandStatus.SUCCESS));

                    responseFuture.addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture channelFuture) {
                            ctx.pipeline().remove(SocksServerConnectHandler.this);
                            outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
                            ctx.pipeline().addLast(new RelayHandler(outboundChannel));
                        }
                    });
                } else {
                    ctx.channel().writeAndFlush(
                            new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });

        final Channel inboundChannel = ctx.channel();
        b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new DirectClientHandler(promise));

        b.connect(request.dstAddr(), request.dstPort()).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    // Connection established use handler provided results
                } else {
                    // Close the connection if the connection attempt has failed.
                    ctx.channel().writeAndFlush(
                            new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });
    } else if (message instanceof Socks5CommandRequest) {
        final Socks5CommandRequest request = (Socks5CommandRequest) message;
        Promise<Channel> promise = ctx.executor().newPromise();
        promise.addListener(new FutureListener<Channel>() {
            @Override
            public void operationComplete(final Future<Channel> future) throws Exception {
                final Channel outboundChannel = future.getNow();
                if (future.isSuccess()) {
                    ChannelFuture responseFuture = ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(
                            Socks5CommandStatus.SUCCESS, request.dstAddrType()));

                    responseFuture.addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture channelFuture) {
                            ctx.pipeline().remove(SocksServerConnectHandler.this);
                            outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
                            ctx.pipeline().addLast(new RelayHandler(outboundChannel));
                        }
                    });
                } else {
                    ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE,
                            request.dstAddrType()));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });

        final Channel inboundChannel = ctx.channel();
        b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new DirectClientHandler(promise));

        b.connect(request.dstAddr(), request.dstPort()).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    // Connection established use handler provided results
                } else {
                    // Close the connection if the connection attempt has failed.
                    ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE,
                            request.dstAddrType()));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });
    } else {
        ctx.close();
    }
}

From source file:com.look.remoting.netty.NettyRemotingClient.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 a2s. c  o  m*/
                public Thread newThread(Runnable r) {
                    return new Thread(r, "NettyClientWorkerThread_" + this.threadIndex.incrementAndGet());
                }
            });

    Bootstrap handler = this.bootstrap.group(this.eventLoopGroupWorker).channel(NioSocketChannel.class)//
            //
            .option(ChannelOption.TCP_NODELAY, true)
            //
            .option(ChannelOption.SO_KEEPALIVE, false)
            //
            .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 NettyConnetManageHandler(), //
                            new NettyClientHandler());
                }
            });

    this.timer.scheduleAtFixedRate(new TimerTask() {

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

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

From source file:com.magnet.yak.load.NettyClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    String host = "54.148.43.16";
    int port = 5222;
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {//from   w w w.j a  v  a2s.c o  m
        Bootstrap b = new Bootstrap(); // (1)
        b.group(workerGroup); // (2)
        b.channel(NioSocketChannel.class); // (3)

        b.option(ChannelOption.SO_KEEPALIVE, true); // (4)
        b.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new XMPPHandler());
            }
        });

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

        f.await();

        Channel channel = f.channel();
        LOGGER.trace("main : Writing {}");
        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
    }
}

From source file:com.mc.netty.server.NettyServer.java

License:Open Source License

private ServerBootstrap getDefaultServerBootstrap() {
    ServerBootstrap bootStrap = new ServerBootstrap();
    bootStrap.group(bossGroup, workerGroup).option(ChannelOption.SO_BACKLOG, 1000)
            // ???
            .option(ChannelOption.SO_SNDBUF, 32 * 1024).option(ChannelOption.SO_RCVBUF, 32 * 1024)
            .option(ChannelOption.TCP_NODELAY, true)
            // ???
            .option(ChannelOption.RCVBUF_ALLOCATOR, AdaptiveRecvByteBufAllocator.DEFAULT)
            .channel(NioServerSocketChannel.class).childOption(ChannelOption.SO_KEEPALIVE, true);

    return bootStrap;
}

From source file:com.miko.s4netty.config.WorkerNettyConfig.java

License:Open Source License

@Bean(name = "tcpChannelOptions")
public Map<ChannelOption<?>, Object> tcpChannelOptions() {

    Map<ChannelOption<?>, Object> options = new HashMap<>();
    options.put(ChannelOption.SO_REUSEADDR, true);
    options.put(ChannelOption.SO_KEEPALIVE, keepAlive);

    logger.debug("tcpChannelOptions = " + options);
    return options;
}

From source file:com.mnxfst.stream.server.StreamAnalyzerServer.java

License:Apache License

public void run(final String configurationFilename, final int port) throws Exception {

    ObjectMapper mapper = new ObjectMapper();
    StreamAnalyzerConfiguration streamAnalyzerConfiguration = mapper.readValue(new File(configurationFilename),
            StreamAnalyzerConfiguration.class);

    // set up  the actor runtime environment
    this.rootActorSystem = ActorSystem.create("streamanalyzer");

    this.componentRegistryRef = componentRegistryInitialization();
    pipelineInitialization(streamAnalyzerConfiguration.getPipelines());
    dispatcherInitialization(streamAnalyzerConfiguration.getDispatchers(), componentRegistryRef);
    listenerInitialization(streamAnalyzerConfiguration.getListeners(), componentRegistryRef);

    EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {//from  w  ww.jav a  2s  .  c o  m
        ServerBootstrap b = new ServerBootstrap(); // (2)
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) // (3)
                .childHandler(new ChannelInitializer<SocketChannel>() { // (4)
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StreamAnalyzerStatsHandler());
                    }
                }).option(ChannelOption.SO_BACKLOG, 128) // (5)
                .childOption(ChannelOption.SO_KEEPALIVE, true); // (6)

        // Bind and start to accept incoming connections.
        ChannelFuture f = b.bind(port).sync(); // (7)

        // Wait until the server socket is closed.
        // In this example, this does not happen, but you can do that to gracefully
        // shut down your server.
        f.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }

}

From source file:com.mobius.software.android.iotbroker.mqtt.net.TCPClient.java

License:Open Source License

public boolean init(final ConnectionListener listener) {
    if (channel == null) {
        bootstrap = new Bootstrap();
        loopGroup = new NioEventLoopGroup(workerThreads);
        bootstrap.group(loopGroup);/*from   ww w  .ja v a2s .  c om*/
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.option(ChannelOption.TCP_NODELAY, true);
        bootstrap.option(ChannelOption.SO_KEEPALIVE, true);

        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                socketChannel.pipeline().addLast(new MQDecoder());
                socketChannel.pipeline().addLast("handler", new MQHandler(listener));
                socketChannel.pipeline().addLast(new MQEncoder());
                socketChannel.pipeline().addLast(new ExceptionHandler(listener));
            }
        });
        bootstrap.remoteAddress(address);

        try {
            channelConnect = bootstrap.connect().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
            return false;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }

    return true;
}

From source file:com.mobius.software.mqtt.performance.controller.net.MqClientBootstrap.java

License:Open Source License

public void init(SocketAddress serverAddress) throws InterruptedException {
    this.serverAddress = serverAddress;
    if (pipelineInitialized.compareAndSet(false, true)) {
        bootstrap.group(loopGroup);//from  www .  jav a 2 s.c  o  m
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.option(ChannelOption.TCP_NODELAY, true);
        bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                socketChannel.pipeline().addLast(new Decoder());
                socketChannel.pipeline().addLast(new Encoder());
                socketChannel.pipeline().addLast("handler", new MqttHandler(clientListeners));
                socketChannel.pipeline().addLast(new ExceptionHandler());
            }
        });
        bootstrap.remoteAddress(serverAddress);
    }
}

From source file:com.mobius.software.mqtt.performance.controller.net.WsClientBootstrap.java

License:Open Source License

@Override
public void init(SocketAddress serverAddress) throws InterruptedException {
    this.serverAddress = serverAddress;
    if (pipelineInitialized.compareAndSet(false, true)) {
        try {//from   ww w .  j  a  v  a  2  s . c  o m
            InetSocketAddress remote = (InetSocketAddress) serverAddress;
            URI uri = new URI("ws://" + remote.getHostString() + ":" + remote.getPort() + "/ws");

            bootstrap.group(loopGroup);
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.option(ChannelOption.TCP_NODELAY, true);
            bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    socketChannel.pipeline().addLast("http-codec", new HttpClientCodec());
                    socketChannel.pipeline().addLast("aggregator", new HttpObjectAggregator(65536));
                    socketChannel.pipeline().addLast("handler",
                            new WsClientHandler(
                                    WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13,
                                            null, false, EmptyHttpHeaders.INSTANCE, 1280000, true, true),
                                    clientListeners));
                    socketChannel.pipeline().addLast("compressor", WebSocketClientCompressionHandler.INSTANCE);
                    socketChannel.pipeline().addLast("exceptionHandler", exceptionHandler);
                }
            });
            bootstrap.remoteAddress(serverAddress);
        } catch (URISyntaxException e) {
            throw new InterruptedException(e.getMessage());
        }
    }
}

From source file:com.mongodb.connection.netty.NettyStream.java

License:Apache License

@Override
public void openAsync(final AsyncCompletionHandler<Void> handler) {
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(workerGroup);/*w  ww .j  ava  2  s  .  c  o m*/
    bootstrap.channel(NioSocketChannel.class);

    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, settings.getConnectTimeout(MILLISECONDS));
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, settings.isKeepAlive());

    if (settings.getReceiveBufferSize() > 0) {
        bootstrap.option(ChannelOption.SO_RCVBUF, settings.getReceiveBufferSize());
    }
    if (settings.getSendBufferSize() > 0) {
        bootstrap.option(ChannelOption.SO_SNDBUF, settings.getSendBufferSize());
    }
    bootstrap.option(ChannelOption.ALLOCATOR, allocator);

    bootstrap.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(final SocketChannel ch) throws Exception {
            if (sslSettings.isEnabled()) {
                SSLEngine engine = SSLContext.getDefault().createSSLEngine(address.getHost(),
                        address.getPort());
                engine.setUseClientMode(true);
                if (!sslSettings.isInvalidHostNameAllowed()) {
                    engine.setSSLParameters(enableHostNameVerification(engine.getSSLParameters()));
                }
                ch.pipeline().addFirst("ssl", new SslHandler(engine, false));
            }
            ch.pipeline().addLast("readTimeoutHandler",
                    new ReadTimeoutHandler(settings.getReadTimeout(MILLISECONDS), MILLISECONDS));
            ch.pipeline().addLast(new InboundBufferHandler());
        }
    });
    final ChannelFuture channelFuture = bootstrap.connect(address.getHost(), address.getPort());
    channelFuture.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(final ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                channel = channelFuture.channel();
                handler.completed(null);
            } else {
                handler.failed(future.cause());
            }
        }
    });
}