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:io.moquette.testclient.Client.java

License:Open Source License

public Client(String host, int port) {

    handler.setClient(this);

    workerGroup = new NioEventLoopGroup();

    try {//from  w w w .j ava 2s .  com
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast("decoder", new MQTTDecoder());
                pipeline.addLast("encoder", new MQTTEncoder());
                pipeline.addLast("handler", handler);
            }
        });

        // Start the client.
        m_channel = b.connect(host, port).sync().channel();
    } catch (Exception ex) {
        LOG.error("Error received in client setup", ex);
        workerGroup.shutdownGracefully();
    }
}

From source file:io.mycat.netty.NettyServer.java

License:Apache License

private ServerBootstrap configServer() {
    bossGroup = new NioEventLoopGroup(args.bossThreads, new DefaultThreadFactory("NettyBossGroup", true));
    workerGroup = new NioEventLoopGroup(args.workerThreads, new DefaultThreadFactory("NettyWorkerGroup", true));
    userExecutor = createUserThreadExecutor();

    final ProtocolHandler handshakeHandler = newHandshakeHandler(userExecutor);
    final ProtocolHandler protocolHandler = newProtocolHandler(userExecutor);

    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childOption(ChannelOption.SO_REUSEADDR, true).childOption(ChannelOption.SO_KEEPALIVE, true)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.TCP_NODELAY, true);

    if (args.socketTimeoutMills > 0) {
        b.childOption(ChannelOption.SO_TIMEOUT, args.socketTimeoutMills);
    }/*from   w ww.  j a  v a  2  s  . c  o  m*/

    if (args.recvBuff > 0) {
        b.childOption(ChannelOption.SO_RCVBUF, args.recvBuff);
    }

    if (args.sendBuff > 0) {
        b.childOption(ChannelOption.SO_SNDBUF, args.sendBuff);
    }

    b.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(createProtocolDecoder(), /* createProtocolEncoder(), */ handshakeHandler,
                    protocolHandler);
        }
    });

    return b;
}

From source file:io.netlibs.bgp.netty.service.BGPv4Client.java

License:Apache License

public ChannelFuture startClient(final PeerConfiguration peerConfiguration) {

    final Bootstrap b = new Bootstrap();

    b.group(workerGroup);//  w  w w  .jav  a 2 s  .  com
    b.channel(NioSocketChannel.class);

    b.option(ChannelOption.TCP_NODELAY, true);
    b.option(ChannelOption.SO_KEEPALIVE, true);

    b.handler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(final SocketChannel ch) throws Exception {
            ch.pipeline().addLast(BGPv4Reframer.HANDLER_NAME, new BGPv4Reframer());
            ch.pipeline().addLast(BGPv4Codec.HANDLER_NAME, new BGPv4Codec(BGPv4PacketDecoder.getInstance()));
            ch.pipeline().addLast(InboundOpenCapabilitiesProcessor.HANDLER_NAME,
                    new InboundOpenCapabilitiesProcessor());
            ch.pipeline().addLast(ValidateServerIdentifier.HANDLER_NAME, new ValidateServerIdentifier());
            ch.pipeline().addLast(BGPv4ClientEndpoint.HANDLER_NAME,
                    new BGPv4ClientEndpoint(BGPv4Client.this.registry));
        }

    });

    // Start the client.
    return b.connect(peerConfiguration.getClientConfig().getRemoteAddress());

}

From source file:io.netlibs.bgp.netty.service.BGPv4Server.java

License:Apache License

public void startServer() {

    ServerBootstrap bootstrap = new ServerBootstrap();

    bootstrap.group(new NioEventLoopGroup(), new NioEventLoopGroup());

    bootstrap.channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
        @Override/*from   w w  w.  j  a va2s .co m*/
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast(BGPv4Reframer.HANDLER_NAME, BGPv4Server.this.reframer);
            pipeline.addLast(BGPv4Codec.HANDLER_NAME, BGPv4Server.this.codec);
            pipeline.addLast(InboundOpenCapabilitiesProcessor.HANDLER_NAME,
                    BGPv4Server.this.inboundOpenCapProcessor);
            pipeline.addLast(ValidateServerIdentifier.HANDLER_NAME, BGPv4Server.this.validateServer);
            pipeline.addLast(BGPv4ServerEndpoint.HANDLER_NAME, BGPv4Server.this.serverEndpoint);
        }
    });

    bootstrap.option(ChannelOption.SO_BACKLOG, 128);

    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.childOption(ChannelOption.TCP_NODELAY, true);

    log.info("Starting local server");

    this.serverChannel = bootstrap.bind(applicationConfiguration.getServerPort()).syncUninterruptibly()
            .channel();

}

From source file:io.netty.example.http2.helloworld.client.Http2Client.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {//  ww  w  .j  av  a2 s .com
        SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;
        sslCtx = SslContextBuilder.forClient().sslProvider(provider)
                /* NOTE: the cipher filter may not include all ciphers required by the HTTP/2 specification.
                 * Please refer to the HTTP/2 specification for cipher requirements. */
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                .trustManager(InsecureTrustManagerFactory.INSTANCE)
                .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.ALPN,
                        // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers.
                        SelectorFailureBehavior.NO_ADVERTISE,
                        // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers.
                        SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2,
                        ApplicationProtocolNames.HTTP_1_1))
                .build();
    } else {
        sslCtx = null;
    }

    EventLoopGroup workerGroup = new NioEventLoopGroup();
    Http2ClientInitializer initializer = new Http2ClientInitializer(sslCtx, Integer.MAX_VALUE);

    try {
        // Configure the client.
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.remoteAddress(HOST, PORT);
        b.handler(initializer);

        // Start the client.
        Channel channel = b.connect().syncUninterruptibly().channel();
        System.out.println("Connected to [" + HOST + ':' + PORT + ']');

        // Wait for the HTTP/2 upgrade to occur.
        Http2SettingsHandler http2SettingsHandler = initializer.settingsHandler();
        http2SettingsHandler.awaitSettings(5, TimeUnit.SECONDS);

        HttpResponseHandler responseHandler = initializer.responseHandler();
        int streamId = 3;
        HttpScheme scheme = SSL ? HttpScheme.HTTPS : HttpScheme.HTTP;
        AsciiString hostName = new AsciiString(HOST + ':' + PORT);
        System.err.println("Sending request(s)...");
        if (URL != null) {
            // Create a simple GET request.
            FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET, URL, Unpooled.EMPTY_BUFFER);
            request.headers().add(HttpHeaderNames.HOST, hostName);
            request.headers().add(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), scheme.name());
            request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
            request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE);
            responseHandler.put(streamId, channel.write(request), channel.newPromise());
            streamId += 2;
        }
        if (URL2 != null) {
            // Create a simple POST request with a body.
            FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, POST, URL2,
                    wrappedBuffer(URL2DATA.getBytes(CharsetUtil.UTF_8)));
            request.headers().add(HttpHeaderNames.HOST, hostName);
            request.headers().add(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), scheme.name());
            request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
            request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE);
            responseHandler.put(streamId, channel.write(request), channel.newPromise());
        }
        channel.flush();
        responseHandler.awaitResponses(5, TimeUnit.SECONDS);
        System.out.println("Finished HTTP/2 request(s)");

        // Wait until the connection is closed.
        channel.close().syncUninterruptibly();
    } finally {
        workerGroup.shutdownGracefully();
    }
}

From source file:io.netty.example.spdy.client.SpdyClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE)
            .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.NPN,
                    // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers.
                    SelectorFailureBehavior.NO_ADVERTISE,
                    // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers.
                    SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.SPDY_3_1,
                    ApplicationProtocolNames.HTTP_1_1))
            .build();/* w w  w  . j a  v a 2s  .  c o  m*/

    HttpResponseClientHandler httpResponseHandler = new HttpResponseClientHandler();
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.remoteAddress(HOST, PORT);
        b.handler(new SpdyClientInitializer(sslCtx, httpResponseHandler));

        // Start the client.
        Channel channel = b.connect().syncUninterruptibly().channel();
        System.out.println("Connected to " + HOST + ':' + PORT);

        // Create a GET request.
        HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "",
                Unpooled.EMPTY_BUFFER);
        request.headers().set(HttpHeaderNames.HOST, HOST);
        request.headers().set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);

        // Send the GET request.
        channel.writeAndFlush(request).sync();

        // Waits for the complete HTTP response
        httpResponseHandler.queue().take().sync();
        System.out.println("Finished SPDY HTTP GET");

        // Wait until the connection is closed.
        channel.close().syncUninterruptibly();
    } finally {
        workerGroup.shutdownGracefully();
    }
}

From source file:io.reactivex.netty.client.AbstractClientBuilder.java

License:Apache License

public B defaultTcpOptions() {
    defaultChannelOptions();
    channelOption(ChannelOption.SO_KEEPALIVE, true);
    return channelOption(ChannelOption.TCP_NODELAY, true);
}

From source file:io.reactivex.netty.server.ConnectionBasedServerBuilder.java

License:Apache License

@Override
public B defaultChannelOptions() {
    channelOption(ChannelOption.SO_KEEPALIVE, true);
    childChannelOption(ChannelOption.SO_KEEPALIVE, true);
    childChannelOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    return super.defaultChannelOptions();
}

From source file:io.tetrapod.core.flashpolicy.FlashPolicyServer.java

License:Apache License

@Override
protected void setOptions(ServerBootstrap sb) {
    sb.childOption(ChannelOption.TCP_NODELAY, true);
    sb.childOption(ChannelOption.SO_KEEPALIVE, true);
}

From source file:io.tilt.minka.broker.impl.SocketServer.java

License:Apache License

private boolean keepListening() {
    boolean disconnected;
    logger.info("{}: ({}:{}) Building server (using i: {}) with up to {} concurrent requests",
            getClass().getSimpleName(), serverAddress, serverPort, networkInterfase,
            this.connectionHandlerThreads);

    try {/*from  w w w  .  j av  a 2 s.  co m*/
        final ServerBootstrap b = new ServerBootstrap();
        b.group(serverWorkerGroup).channel(NioServerSocketChannel.class)
                //.channel(OioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new ObjectEncoder(),
                                new ObjectDecoder(ClassResolvers.cacheDisabled(null)), serverHandler);
                    }
                });
        logger.info("{}: Listening for client connections..", getClass().getSimpleName());
        b.childOption(ChannelOption.SO_KEEPALIVE, true);

        logger.info(
                "{}: ({}:{}) Listening to client connections (using i:{}) with up to {} concurrent requests",
                getClass().getSimpleName(), serverAddress, serverPort, networkInterfase,
                this.connectionHandlerThreads);

        b.bind(this.serverAddress, this.serverPort).sync().channel().closeFuture().sync();
        disconnected = false;
    } catch (Exception e) {
        disconnected = true;
        logger.error("{}: ({}:{}) Unexpected interruption while listening incoming connections",
                getClass().getSimpleName(), serverAddress, serverPort, e);
    } finally {
        logger.info("{}: ({}:{}) Exiting server listening scope", getClass().getSimpleName(), serverAddress,
                serverPort);
        shutdown();
    }
    return disconnected;
}