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.undertow.server.protocol.http2.HTTP2ViaUpgradeTestCase.java

License:Open Source License

@Test
public void testHttp2WithNettyClient() throws Exception {

    message = "Hello World";

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

    try {/*from ww  w  .ja v a 2s .c  om*/
        // Configure the client.
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        final int port = DefaultServer.getHostPort("default") + 1;
        final String host = DefaultServer.getHostAddress("default");
        b.remoteAddress(host, port);
        b.handler(initializer);

        // Start the client.

        Channel channel = b.connect().syncUninterruptibly().channel();

        Http2SettingsHandler http2SettingsHandler = initializer.settingsHandler();
        http2SettingsHandler.awaitSettings(5, TimeUnit.SECONDS);
        HttpResponseHandler responseHandler = initializer.responseHandler();
        int streamId = 3;
        URI hostName = URI.create("http://" + host + ':' + port);
        System.err.println("Sending request(s)...");
        // Create a simple GET request.
        final ChannelPromise promise = channel.newPromise();
        responseHandler.put(streamId, promise);
        FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
                hostName.toString());
        request.headers().add(HttpHeaderNames.HOST, hostName);
        request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
        request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE);
        channel.writeAndFlush(request);
        streamId += 2;
        promise.await(10, TimeUnit.SECONDS);
        Assert.assertEquals(message, messages.poll());
        System.out.println("Finished HTTP/2 request(s)");

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

From source file:io.vertx.core.http.impl.HttpClientImpl.java

License:Open Source License

private void applyConnectionOptions(Bootstrap bootstrap) {
    bootstrap.option(ChannelOption.TCP_NODELAY, options.isTcpNoDelay());
    if (options.getSendBufferSize() != -1) {
        bootstrap.option(ChannelOption.SO_SNDBUF, options.getSendBufferSize());
    }/*from w w w . j a v a 2s .  c o m*/
    if (options.getReceiveBufferSize() != -1) {
        bootstrap.option(ChannelOption.SO_RCVBUF, options.getReceiveBufferSize());
        bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR,
                new FixedRecvByteBufAllocator(options.getReceiveBufferSize()));
    }
    bootstrap.option(ChannelOption.SO_LINGER, options.getSoLinger());
    if (options.getTrafficClass() != -1) {
        bootstrap.option(ChannelOption.IP_TOS, options.getTrafficClass());
    }
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, options.getConnectTimeout());
    bootstrap.option(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, options.isTcpKeepAlive());
    bootstrap.option(ChannelOption.SO_REUSEADDR, options.isReuseAddress());
}

From source file:io.vertx.core.net.impl.NetClientBase.java

License:Open Source License

private void applyConnectionOptions(Bootstrap bootstrap) {
    if (options.getLocalAddress() != null) {
        bootstrap.localAddress(options.getLocalAddress(), 0);
    }/*from  w w  w.java 2  s  . co  m*/
    bootstrap.option(ChannelOption.TCP_NODELAY, options.isTcpNoDelay());
    if (options.getSendBufferSize() != -1) {
        bootstrap.option(ChannelOption.SO_SNDBUF, options.getSendBufferSize());
    }
    if (options.getReceiveBufferSize() != -1) {
        bootstrap.option(ChannelOption.SO_RCVBUF, options.getReceiveBufferSize());
        bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR,
                new FixedRecvByteBufAllocator(options.getReceiveBufferSize()));
    }
    if (options.getSoLinger() != -1) {
        bootstrap.option(ChannelOption.SO_LINGER, options.getSoLinger());
    }
    if (options.getTrafficClass() != -1) {
        bootstrap.option(ChannelOption.IP_TOS, options.getTrafficClass());
    }
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, options.getConnectTimeout());
    bootstrap.option(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, options.isTcpKeepAlive());
}

From source file:io.vertx.core.net.impl.NetServerBase.java

License:Open Source License

/**
 * Apply the connection option to the server.
 *
 * @param bootstrap the Netty server bootstrap
 *//*from w  ww  . j a  v a2 s . co  m*/
protected void applyConnectionOptions(ServerBootstrap bootstrap) {
    bootstrap.childOption(ChannelOption.TCP_NODELAY, options.isTcpNoDelay());
    if (options.getSendBufferSize() != -1) {
        bootstrap.childOption(ChannelOption.SO_SNDBUF, options.getSendBufferSize());
    }
    if (options.getReceiveBufferSize() != -1) {
        bootstrap.childOption(ChannelOption.SO_RCVBUF, options.getReceiveBufferSize());
        bootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR,
                new FixedRecvByteBufAllocator(options.getReceiveBufferSize()));
    }
    if (options.getSoLinger() != -1) {
        bootstrap.option(ChannelOption.SO_LINGER, options.getSoLinger());
    }
    if (options.getTrafficClass() != -1) {
        bootstrap.childOption(ChannelOption.IP_TOS, options.getTrafficClass());
    }
    bootstrap.childOption(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE);

    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, options.isTcpKeepAlive());
    bootstrap.option(ChannelOption.SO_REUSEADDR, options.isReuseAddress());
    if (options.getAcceptBacklog() != -1) {
        bootstrap.option(ChannelOption.SO_BACKLOG, options.getAcceptBacklog());
    }
}

From source file:io.vertx.core.net.impl.transport.Transport.java

License:Open Source License

public void configure(ClientOptionsBase options, Bootstrap bootstrap) {
    if (options.getLocalAddress() != null) {
        bootstrap.localAddress(options.getLocalAddress(), 0);
    }//  ww w.j a v  a  2 s.co m
    bootstrap.option(ChannelOption.TCP_NODELAY, options.isTcpNoDelay());
    if (options.getSendBufferSize() != -1) {
        bootstrap.option(ChannelOption.SO_SNDBUF, options.getSendBufferSize());
    }
    if (options.getReceiveBufferSize() != -1) {
        bootstrap.option(ChannelOption.SO_RCVBUF, options.getReceiveBufferSize());
        bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR,
                new FixedRecvByteBufAllocator(options.getReceiveBufferSize()));
    }
    if (options.getSoLinger() != -1) {
        bootstrap.option(ChannelOption.SO_LINGER, options.getSoLinger());
    }
    if (options.getTrafficClass() != -1) {
        bootstrap.option(ChannelOption.IP_TOS, options.getTrafficClass());
    }
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, options.getConnectTimeout());
    bootstrap.option(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, options.isTcpKeepAlive());
    bootstrap.option(ChannelOption.SO_REUSEADDR, options.isReuseAddress());
}

From source file:io.vertx.core.net.impl.transport.Transport.java

License:Open Source License

public void configure(NetServerOptions options, ServerBootstrap bootstrap) {
    bootstrap.childOption(ChannelOption.TCP_NODELAY, options.isTcpNoDelay());
    if (options.getSendBufferSize() != -1) {
        bootstrap.childOption(ChannelOption.SO_SNDBUF, options.getSendBufferSize());
    }//  w w  w.  j a  v a 2  s.c om
    if (options.getReceiveBufferSize() != -1) {
        bootstrap.childOption(ChannelOption.SO_RCVBUF, options.getReceiveBufferSize());
        bootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR,
                new FixedRecvByteBufAllocator(options.getReceiveBufferSize()));
    }
    if (options.getSoLinger() != -1) {
        bootstrap.childOption(ChannelOption.SO_LINGER, options.getSoLinger());
    }
    if (options.getTrafficClass() != -1) {
        bootstrap.childOption(ChannelOption.IP_TOS, options.getTrafficClass());
    }
    bootstrap.childOption(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE);
    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, options.isTcpKeepAlive());
    bootstrap.option(ChannelOption.SO_REUSEADDR, options.isReuseAddress());
    if (options.getAcceptBacklog() != -1) {
        bootstrap.option(ChannelOption.SO_BACKLOG, options.getAcceptBacklog());
    }
}

From source file:ipLock.SignalClient.java

License:Open Source License

public void connect(int port, final SignalHandler handler) throws InterruptedException {
    workerGroup = new NioEventLoopGroup();

    Bootstrap b = new Bootstrap();
    b.group(workerGroup);/*from  ww w .  j  a v  a2s  .  c om*/
    b.channel(NioSocketChannel.class);
    b.option(ChannelOption.SO_KEEPALIVE, true);
    b.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(new LineBasedFrameDecoder(MAX_LINE_LENGTH),
                    new StringDecoder(CharsetUtil.UTF_8), new StringEncoder(CharsetUtil.UTF_8),
                    new SignalDecoder(), new SignalEncoder(), new SignalClientHandlerAdapter(handler));
        }
    });

    String host = "localhost";
    channel = b.connect(host, port).sync().channel();
    LOGGER.info("connected to signal server at tcp://{}:{}", host, port);
}

From source file:ipLock.SignalServer.java

License:Open Source License

public void start(final int port) throws InterruptedException {
    synchronized (this) {
        if (running) {
            throw new IllegalStateException("signal server already running");
        }/*from w  w w . j a  va 2 s  .  c  om*/

        bossGroup = new NioEventLoopGroup();
        workerGroup = new NioEventLoopGroup();

        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new SignalChannelInitializer()).option(ChannelOption.SO_BACKLOG, 128)
                .childOption(ChannelOption.SO_KEEPALIVE, true);

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

        LOGGER.info("signal server listening on tcp://localhost:{}", port);
        running = true;
    }
}

From source file:it.jnrpe.JNRPE.java

License:Apache License

/**
 * Creates and returns a configured NETTY ServerBootstrap object.
 * /*from  ww  w.j a  v a  2s  .  c o  m*/
 * @param useSSL
 *            <code>true</code> if SSL must be used.
        
 * @return the server bootstrap object */
private ServerBootstrap getServerBootstrap(final boolean useSSL) {

    final CommandInvoker invoker = new CommandInvoker(pluginRepository, commandRepository, acceptParams,
            getExecutionContext());

    final ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(final SocketChannel ch) throws Exception {

                    if (useSSL) {
                        final SSLEngine engine = getSSLEngine();
                        engine.setEnabledCipherSuites(engine.getSupportedCipherSuites());
                        engine.setUseClientMode(false);
                        engine.setNeedClientAuth(false);
                        ch.pipeline().addLast("ssl", new SslHandler(engine));
                    }

                    ch.pipeline()
                            .addLast(new JNRPERequestDecoder(), new JNRPEResponseEncoder(),
                                    new JNRPEServerHandler(invoker, context))
                            .addLast("idleStateHandler", new IdleStateHandler(readTimeout, writeTimeout, 0))
                            .addLast("jnrpeIdleStateHandler", new JNRPEIdleStateHandler(context));
                }
            }).option(ChannelOption.SO_BACKLOG, maxAcceptedConnections)
            .childOption(ChannelOption.SO_KEEPALIVE, Boolean.TRUE);

    return serverBootstrap;
}

From source file:jetty.cdi.CDINettyJaxrsServer.java

License:Apache License

@Override
public void start() {
    eventLoopGroup = new NioEventLoopGroup(ioWorkerCount);
    eventExecutor = new NioEventLoopGroup(executorThreadCount);
    deployment.start();//from w  w  w. j av a2s  .c om
    // this is the only line that's different in the whole class.
    final RequestDispatcher dispatcher = this.createRequestDispatcher();
    // Configure the server.
    if (sslContext == null) {
        bootstrap.group(eventLoopGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new HttpRequestDecoder());
                        ch.pipeline().addLast(new HttpObjectAggregator(maxRequestSize));
                        ch.pipeline().addLast(new HttpResponseEncoder());
                        ch.pipeline().addLast(new RestEasyHttpRequestDecoder(dispatcher.getDispatcher(), root,
                                RestEasyHttpRequestDecoder.Protocol.HTTP));
                        ch.pipeline().addLast(new RestEasyHttpResponseEncoder(dispatcher));
                        ch.pipeline().addLast(eventExecutor, new RequestHandler(dispatcher));
                    }
                }).option(ChannelOption.SO_BACKLOG, backlog).childOption(ChannelOption.SO_KEEPALIVE, true);
    } else {
        final SSLEngine engine = sslContext.createSSLEngine();
        engine.setUseClientMode(false);
        bootstrap.group(eventLoopGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addFirst(new SslHandler(engine));
                        ch.pipeline().addLast(new HttpRequestDecoder());
                        ch.pipeline().addLast(new HttpObjectAggregator(maxRequestSize));
                        ch.pipeline().addLast(new HttpResponseEncoder());
                        ch.pipeline().addLast(new RestEasyHttpRequestDecoder(dispatcher.getDispatcher(), root,
                                RestEasyHttpRequestDecoder.Protocol.HTTPS));
                        ch.pipeline().addLast(new RestEasyHttpResponseEncoder(dispatcher));
                        ch.pipeline().addLast(eventExecutor, new RequestHandler(dispatcher));

                    }
                }).option(ChannelOption.SO_BACKLOG, backlog).childOption(ChannelOption.SO_KEEPALIVE, true);
    }

    bootstrap.bind(port).syncUninterruptibly();
}