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.atomix.catalyst.transport.NettyClient.java

License:Apache License

@Override
public CompletableFuture<Connection> connect(Address address) {
    Assert.notNull(address, "address");
    ThreadContext context = ThreadContext.currentContextOrThrow();
    CompletableFuture<Connection> future = new ComposableFuture<>();

    LOGGER.info("Connecting to {}", address);

    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(eventLoopGroup).channel(
            eventLoopGroup instanceof EpollEventLoopGroup ? EpollSocketChannel.class : NioSocketChannel.class)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override/*from   w  w  w .  ja v  a2  s.c  om*/
                protected void initChannel(SocketChannel channel) throws Exception {
                    ChannelPipeline pipeline = channel.pipeline();
                    pipeline.addLast(FIELD_PREPENDER);
                    pipeline.addLast(new LengthFieldBasedFrameDecoder(1024 * 32, 0, 2, 0, 2));
                    pipeline.addLast(new NettyHandler(connections, future::complete, context));
                }
            });

    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000);
    bootstrap.option(ChannelOption.ALLOCATOR, ALLOCATOR);

    bootstrap.connect(address.socketAddress()).addListener(channelFuture -> {
        if (channelFuture.isSuccess()) {
            LOGGER.info("Connected to {}", address);
        } else {
            context.execute(() -> future.completeExceptionally(channelFuture.cause()));
        }
    });
    return future;
}

From source file:io.atomix.catalyst.transport.NettyServer.java

License:Apache License

/**
 * Starts listening for the given member.
 *///from w ww .  j  a v a 2s .c om
private void listen(Address address, Consumer<Connection> listener, ThreadContext context) {
    channelGroup = new DefaultChannelGroup("catalyst-acceptor-channels", GlobalEventExecutor.INSTANCE);

    handler = new ServerHandler(connections, listener, context);

    final ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(eventLoopGroup)
            .channel(eventLoopGroup instanceof EpollEventLoopGroup ? EpollServerSocketChannel.class
                    : NioServerSocketChannel.class)
            .handler(new LoggingHandler(LogLevel.DEBUG)).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel channel) throws Exception {
                    ChannelPipeline pipeline = channel.pipeline();
                    pipeline.addLast(FIELD_PREPENDER);
                    pipeline.addLast(new LengthFieldBasedFrameDecoder(1024 * 32, 0, 2, 0, 2));
                    pipeline.addLast(handler);
                }
            }).option(ChannelOption.SO_BACKLOG, 128).option(ChannelOption.TCP_NODELAY, true)
            .option(ChannelOption.SO_REUSEADDR, true).childOption(ChannelOption.ALLOCATOR, ALLOCATOR)
            .childOption(ChannelOption.SO_KEEPALIVE, true);

    LOGGER.info("Binding to {}", address);

    ChannelFuture bindFuture = bootstrap.bind(address.socketAddress());
    bindFuture.addListener((ChannelFutureListener) channelFuture -> {
        if (channelFuture.isSuccess()) {
            listening = true;
            context.executor().execute(() -> {
                LOGGER.info("Listening at {}", bindFuture.channel().localAddress());
                listenFuture.complete(null);
            });
        } else {
            context.execute(() -> listenFuture.completeExceptionally(channelFuture.cause()));
        }
    });
    channelGroup.add(bindFuture.channel());
}

From source file:io.atomix.cluster.messaging.impl.NettyMessagingService.java

License:Apache License

private Bootstrap bootstrapClient(Address address) {
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    bootstrap.option(ChannelOption.WRITE_BUFFER_WATER_MARK,
            new WriteBufferWaterMark(10 * 32 * 1024, 10 * 64 * 1024));
    bootstrap.option(ChannelOption.SO_RCVBUF, 1024 * 1024);
    bootstrap.option(ChannelOption.SO_SNDBUF, 1024 * 1024);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000);
    bootstrap.group(clientGroup);// w ww . j a  va  2s .c o  m
    // TODO: Make this faster:
    // http://normanmaurer.me/presentations/2014-facebook-eng-netty/slides.html#37.0
    bootstrap.channel(clientChannelClass);
    bootstrap.remoteAddress(address.address(true), address.port());
    if (enableNettyTls) {
        bootstrap.handler(new SslClientCommunicationChannelInitializer());
    } else {
        bootstrap.handler(new BasicChannelInitializer());
    }
    return bootstrap;
}

From source file:io.atomix.cluster.messaging.impl.NettyMessagingService.java

License:Apache License

private CompletableFuture<Void> startAcceptingConnections() {
    CompletableFuture<Void> future = new CompletableFuture<>();
    ServerBootstrap b = new ServerBootstrap();
    b.option(ChannelOption.SO_REUSEADDR, true);
    b.option(ChannelOption.SO_BACKLOG, 128);
    b.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(8 * 1024, 32 * 1024));
    b.childOption(ChannelOption.SO_RCVBUF, 1024 * 1024);
    b.childOption(ChannelOption.SO_SNDBUF, 1024 * 1024);
    b.childOption(ChannelOption.SO_KEEPALIVE, true);
    b.childOption(ChannelOption.TCP_NODELAY, true);
    b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    b.group(serverGroup, clientGroup);/* www .  j  a v a  2 s  . c  om*/
    b.channel(serverChannelClass);
    if (enableNettyTls) {
        b.childHandler(new SslServerCommunicationChannelInitializer());
    } else {
        b.childHandler(new BasicChannelInitializer());
    }

    // Bind and start to accept incoming connections.
    b.bind(localAddress.port()).addListener((ChannelFutureListener) f -> {
        if (f.isSuccess()) {
            log.info("{} accepting incoming connections on port {}", localAddress.address(true),
                    localAddress.port());
            serverChannel = f.channel();
            future.complete(null);
        } else {
            log.warn("{} failed to bind to port {} due to {}", localAddress.address(true), localAddress.port(),
                    f.cause());
            future.completeExceptionally(f.cause());
        }
    });
    return future;
}

From source file:io.awacs.agent.NettyClient.java

License:Apache License

@Override
public void start() {
    try {// ww  w  .  jav  a  2s  . c o  m
        this.bootstrap = new Bootstrap();
        this.group = new NioEventLoopGroup();
        bootstrap.group(group);
        bootstrap.channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.SO_KEEPALIVE, true).handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new BinaryMessageDecoder());
                        pipeline.addLast(new BinaryMessageEncoder());
                    }
                });

        pool = new NettyChannelPool(bootstrap, addresses);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:io.awacs.server.MessageReportServer.java

License:Apache License

@Override
public void start() {
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(boss, worker).channel(NioServerSocketChannel.class)
            .handler(new LoggingHandler(LogLevel.DEBUG)).childHandler(new ChannelInitializer<SocketChannel>() {

                @Override/*from w ww  . j ava  2  s.  c o m*/
                protected void initChannel(SocketChannel ch) throws Exception {
                    //??
                    ch.pipeline().addLast(new BinaryMessageDecoder());
                    ch.pipeline().addLast(new BinaryMessageEncoder());
                    //
                    ch.pipeline().addLast(new MessageReportRouter(MessageReportServer.this));
                }
            }).childOption(ChannelOption.SO_KEEPALIVE, true);
    try {
        bootstrap.bind(host, port).sync();
    } catch (InterruptedException e) {
        stop();
    }
}

From source file:io.bsoa.rpc.grpc.client12.Http2Client.java

License:Apache License

public static void main(String[] args) throws Exception {

    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {/* w  w  w  . j  a va 2  s  . co m*/
        // Configure the client.
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.remoteAddress(HOST, PORT);

        Http2ClientInitializer initializer = new Http2ClientInitializer(Integer.MAX_VALUE);
        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(500, TimeUnit.SECONDS);

        HttpResponseHandler responseHandler = initializer.responseHandler();
        int streamId = 3;
        HttpScheme scheme = HttpScheme.HTTP;
        AsciiString hostName = new AsciiString(HOST + ':' + PORT);
        System.err.println("Sending request(s)...");

        while (true) {
            try {
                if (URL != null) {
                    // Create a simple GET request.
                    FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET, URL);
                    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.writeAndFlush(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,
                            Unpooled.copiedBuffer(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.writeAndFlush(request), channel.newPromise());
                    streamId += 2;
                }
                responseHandler.awaitResponses(5, TimeUnit.SECONDS);
                System.out.println("Finished HTTP/2 request(s)");

            } catch (Exception e) {
                e.printStackTrace();
            }

            try {
                Thread.sleep(5000);
            } catch (Exception e) {
                // TODO
            }
        }
        // Wait until the connection is closed.
        //            channel.close().syncUninterruptibly();
    } finally {
        workerGroup.shutdownGracefully();
    }
}

From source file:io.crate.mqtt.netty.Client.java

License:Open Source License

public void connect() {
    LOGGER.debug("[mqtt-client] connect");
    handler = new ClientNettyMQTTHandler();
    workerGroup = new NioEventLoopGroup(1);
    try {/*from  w ww  .ja va  2s.  c o  m*/
        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", MqttEncoder.INSTANCE);
                pipeline.addLast("handler", handler);
            }
        });

        // Start the client.
        channel = b.connect(host, port).sync().channel();
    } catch (Exception ex) {
        LOGGER.error("[mqtt-client] Error in client setup: " + ex.getMessage());
        workerGroup.shutdownGracefully();
        Throwables.rethrow(ex);
    }
}

From source file:io.crate.netty.CrateChannelBootstrapFactory.java

License:Apache License

public static ServerBootstrap newChannelBootstrap(String id, Settings settings) {
    EventLoopGroup boss = new NioEventLoopGroup(Netty4Transport.NETTY_BOSS_COUNT.get(settings),
            daemonThreadFactory(settings, id + "-netty-boss"));
    EventLoopGroup worker = new NioEventLoopGroup(Netty4Transport.WORKER_COUNT.get(settings),
            daemonThreadFactory(settings, id + "-netty-worker"));
    Boolean reuseAddress = Netty4Transport.TCP_REUSE_ADDRESS.get(settings);
    return new ServerBootstrap().channel(NioServerSocketChannel.class).group(boss, worker)
            .option(ChannelOption.SO_REUSEADDR, reuseAddress)
            .childOption(ChannelOption.SO_REUSEADDR, reuseAddress)
            .childOption(ChannelOption.TCP_NODELAY, Netty4Transport.TCP_NO_DELAY.get(settings))
            .childOption(ChannelOption.SO_KEEPALIVE, Netty4Transport.TCP_KEEP_ALIVE.get(settings));
}

From source file:io.fouad.jtb.webhook.WebhookServer.java

License:Open Source License

/**
 * Starts receiving requests from Telegram server (WEBHOOK mode). This is a blocking method.
 */// w ww  .j  a v  a2 s .co  m
public void start() throws InterruptedException {
    bossGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup();

    try {
        ServerBootstrap server = new ServerBootstrap();

        server.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ServerInitializer(sslCtx, path)).option(ChannelOption.SO_BACKLOG, 128)
                .childOption(ChannelOption.SO_KEEPALIVE, true);

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

        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}