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.github.milenkovicm.kafka.connection.AbstractKafkaBroker.java

License:Apache License

public AbstractKafkaBroker(String hostname, int port, String topicName, EventLoopGroup workerGroup,
        ProducerProperties properties) {
    this.hostname = hostname;
    this.port = port;
    this.topicName = topicName;
    this.workerGroup = workerGroup;
    this.properties = properties;

    this.bootstrap = new Bootstrap();
    this.bootstrap.group(this.workerGroup);
    this.bootstrap.channel(NioSocketChannel.class);
    this.bootstrap.option(ChannelOption.TCP_NODELAY, true);
    this.bootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK,
            properties.get(ProducerProperties.NETTY_HIGH_WATERMARK));
    this.bootstrap.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK,
            properties.get(ProducerProperties.NETTY_LOW_WATERMARK));

    this.bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    if (properties.get(ProducerProperties.SO_TIMEOUT) > 0) {
        this.bootstrap.option(ChannelOption.SO_TIMEOUT, 0);
    }//  w  ww  .  ja  va2  s.c  om

    if (properties.get(ProducerProperties.SO_RCVBUF) > 0) {
        this.bootstrap.option(ChannelOption.SO_RCVBUF, 0);
    }

    if (properties.get(ProducerProperties.SO_SNDBUF) > 0) {
        this.bootstrap.option(ChannelOption.SO_SNDBUF, 0);
    }

    this.bootstrap.handler(pipeline());
}

From source file:com.github.netfreer.shadowducks.client.handler.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  w  w  .j  a  va 2 s .co  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(), request.dstAddr(), request.dstPort()));

                    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 {
                Attribute<Long> beginTimeAttr = ctx.channel().attr(AttrKeys.CHANNEL_BEGIN_TIME);
                final long parseTime = beginTimeAttr.get();
                long usedTime = System.currentTimeMillis() - parseTime;
                if (future.isSuccess()) {
                    // Connection established use handler provided results
                    logger.info("connect {}:{} success, use time {} millis.", request.dstAddr(),
                            request.dstPort(), usedTime);
                } else {
                    // Close the connection if the connection attempt has failed.
                    ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE,
                            request.dstAddrType()));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                    logger.info("connect {}:{} failure, use time {} millis.", request.dstAddr(),
                            request.dstPort(), usedTime);
                }
                beginTimeAttr.set(null);
            }
        });
    } else {
        ctx.close();
    }
}

From source file:com.github.sinsinpub.pero.backend.ConnectBackendHandler.java

License:Apache License

/**
 * Create new connection context to connect real back-end (may be another proxy).
 * /*  w w w .  j  a va  2s  .c  o  m*/
 * @param inboundChannel
 * @param outboundPromise
 * @param upstreamProxyHandler
 * @return Bootstrap
 */
protected Bootstrap newConnectionBootstrap(final Channel inboundChannel, final Promise<Channel> outboundPromise,
        final ProxyHandler upstreamProxyHandler) {
    final Bootstrap b = new Bootstrap();
    b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, getConnectTimeoutMillis())
            .option(ChannelOption.SO_KEEPALIVE, true)
            .handler(new ProxyChannelInitializer(outboundPromise, upstreamProxyHandler));
    return b;
}

From source file:com.github.sparkfy.network.client.TransportClientFactory.java

License:Apache License

/** Create a completely new {@link TransportClient} to the remote address. */
private TransportClient createClient(InetSocketAddress address) throws IOException {
    logger.debug("Creating new connection to " + address);

    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(workerGroup).channel(socketChannelClass)
            // Disable Nagle's Algorithm since we don't want packets to wait
            .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, conf.connectionTimeoutMs())
            .option(ChannelOption.ALLOCATOR, pooledAllocator);

    final AtomicReference<TransportClient> clientRef = new AtomicReference<TransportClient>();
    final AtomicReference<Channel> channelRef = new AtomicReference<Channel>();

    bootstrap.handler(new ChannelInitializer<SocketChannel>() {
        @Override//from w  w  w  .  ja va 2 s.c o m
        public void initChannel(SocketChannel ch) {
            TransportChannelHandler clientHandler = context.initializePipeline(ch);
            clientRef.set(clientHandler.getClient());
            channelRef.set(ch);
        }
    });

    // Connect to the remote server
    long preConnect = System.nanoTime();
    ChannelFuture cf = bootstrap.connect(address);
    if (!cf.awaitUninterruptibly(conf.connectionTimeoutMs())) {
        throw new IOException(
                String.format("Connecting to %s timed out (%s ms)", address, conf.connectionTimeoutMs()));
    } else if (cf.cause() != null) {
        throw new IOException(String.format("Failed to connect to %s", address), cf.cause());
    }

    TransportClient client = clientRef.get();
    Channel channel = channelRef.get();
    assert client != null : "Channel future completed successfully with null client";

    // Execute any client bootstraps synchronously before marking the Client as successful.
    long preBootstrap = System.nanoTime();
    logger.debug("Connection to {} successful, running bootstraps...", address);
    try {
        for (TransportClientBootstrap clientBootstrap : clientBootstraps) {
            clientBootstrap.doBootstrap(client, channel);
        }
    } catch (Exception e) { // catch non-RuntimeExceptions too as bootstrap may be written in Scala
        long bootstrapTimeMs = (System.nanoTime() - preBootstrap) / 1000000;
        logger.error("Exception while bootstrapping client after " + bootstrapTimeMs + " ms", e);
        client.close();
        throw Throwables.propagate(e);
    }
    long postBootstrap = System.nanoTime();

    logger.debug("Successfully created connection to {} after {} ms ({} ms spent in bootstraps)", address,
            (postBootstrap - preConnect) / 1000000, (postBootstrap - preBootstrap) / 1000000);

    return client;
}

From source file:com.github.vitrifiedcode.javautilities.netty.DiscardServer.java

License:Open Source License

public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*from  w  w  w  .  j  a v a2  s  .  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 DiscardServerHandler());
                    }
                }).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.github.wolf480pl.ircd.netty.NettyServer.java

License:Open Source License

public ChannelFuture start() {
    if (!started.compareAndSet(false, true)) {
        return null;
    }/*from  w w w  . j av a 2 s  . c  om*/

    ServerBootstrap bootstrap = new ServerBootstrap();
    bossGroup = new NioEventLoopGroup(1);
    workerGroup = new NioEventLoopGroup();

    IRCChannelInitializer initializer = new IRCChannelInitializer(handler);

    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(initializer)
            .childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true);

    ChannelFuture future = bootstrap.bind(bindAddress);
    this.channel = future.channel();
    return future;
}

From source file:com.github.zk1931.jzab.NettyTransport.java

License:Apache License

/**
 * Constructs a NettyTransport object./*from  w  ww  .  jav  a  2 s . com*/
 *
 * @param hostPort "hostname:port" string. The netty transport binds to the
 *                 port specified in the string.
 * @param receiver receiver callback.
 * @param sslParam Ssl parameters.
 * @param dir the directory used to store the received file.
 */
public NettyTransport(String hostPort, final Receiver receiver, ZabConfig.SslParameters sslParam,
        final File dir) throws InterruptedException, GeneralSecurityException, IOException {
    super(receiver);
    this.keyStore = sslParam.getKeyStore();
    this.trustStore = sslParam.getTrustStore();
    this.keyStorePassword = sslParam.getKeyStorePassword() != null
            ? sslParam.getKeyStorePassword().toCharArray()
            : null;
    this.trustStorePassword = sslParam.getTrustStorePassword() != null
            ? sslParam.getTrustStorePassword().toCharArray()
            : null;
    this.dir = dir;
    if (isSslEnabled()) {
        initSsl();
    }

    this.hostPort = hostPort;
    String[] address = hostPort.split(":", 2);
    int port = Integer.parseInt(address[1]);
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 128)
            .option(ChannelOption.SO_REUSEADDR, true).childOption(ChannelOption.SO_KEEPALIVE, true)
            .childOption(ChannelOption.TCP_NODELAY, true).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    if (isSslEnabled()) {
                        SSLEngine engine = serverContext.createSSLEngine();
                        engine.setUseClientMode(false);
                        engine.setNeedClientAuth(true);
                        ch.pipeline().addLast(new SslHandler(engine));
                    }
                    // Incoming handlers
                    ch.pipeline().addLast(new MainHandler());
                    ch.pipeline().addLast(new ServerHandshakeHandler());
                    ch.pipeline().addLast(new NotifyHandler());
                    ch.pipeline().addLast(new ServerErrorHandler());
                }
            });

    // Travis build fails once in a while because it fails to bind to a port.
    // This is most likely a transient failure. Retry binding for 5 times with
    // 1 second sleep in between before giving up.
    int bindRetryCount = 5;
    for (int i = 0;; i++) {
        try {
            channel = b.bind(port).sync().channel();
            LOG.info("Server started: {}", hostPort);
            return;
        } catch (Exception ex) {
            if (i >= bindRetryCount) {
                throw ex;
            }
            LOG.debug("Failed to bind to {}. Retrying after 1 second.", hostPort);
            Thread.sleep(1000);
        }
    }
}

From source file:com.github.zk1931.jzab.transport.NettyTransport.java

License:Apache License

/**
 * Constructs a NettyTransport object./*from w  w w . j av a 2s .  c  o m*/
 *
 * @param hostPort "hostname:port" string. The netty transport binds to the
 *                 port specified in the string.
 * @param receiver receiver callback.
 * @param sslParam Ssl parameters.
 * @param dir the directory used to store the received file.
 */
public NettyTransport(String hostPort, final Receiver receiver, SslParameters sslParam, final File dir)
        throws InterruptedException, GeneralSecurityException, IOException {
    super(receiver);
    this.keyStore = sslParam.getKeyStore();
    this.trustStore = sslParam.getTrustStore();
    this.keyStorePassword = sslParam.getKeyStorePassword() != null
            ? sslParam.getKeyStorePassword().toCharArray()
            : null;
    this.trustStorePassword = sslParam.getTrustStorePassword() != null
            ? sslParam.getTrustStorePassword().toCharArray()
            : null;
    this.dir = dir;
    if (isSslEnabled()) {
        initSsl();
    }

    this.hostPort = hostPort;
    String[] address = hostPort.split(":", 2);
    int port = Integer.parseInt(address[1]);
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 128)
            .option(ChannelOption.SO_REUSEADDR, true).childOption(ChannelOption.SO_KEEPALIVE, true)
            .childOption(ChannelOption.TCP_NODELAY, true).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    if (isSslEnabled()) {
                        SSLEngine engine = serverContext.createSSLEngine();
                        engine.setUseClientMode(false);
                        engine.setNeedClientAuth(true);
                        ch.pipeline().addLast(new SslHandler(engine));
                    }
                    // Incoming handlers
                    ch.pipeline().addLast(new MainHandler());
                    ch.pipeline().addLast(new ServerHandshakeHandler());
                    ch.pipeline().addLast(new NotifyHandler());
                    ch.pipeline().addLast(new ErrorHandler());
                    // Outgoing handlers.
                    ch.pipeline().addLast("frameEncoder", new LengthFieldPrepender(4));
                }
            });

    // Travis build fails once in a while because it fails to bind to a port.
    // This is most likely a transient failure. Retry binding for 5 times with
    // 1 second sleep in between before giving up.
    int bindRetryCount = 5;
    for (int i = 0;; i++) {
        try {
            channel = b.bind(port).sync().channel();
            LOG.info("Server started: {}", hostPort);
            return;
        } catch (Exception ex) {
            if (i >= bindRetryCount) {
                throw ex;
            }
            LOG.debug("Failed to bind to {}. Retrying after 1 second.", hostPort);
            Thread.sleep(1000);
        }
    }
}

From source file:com.google.cloud.pubsub.proxy.moquette.NettyAcceptor.java

License:Open Source License

private void initFactory(String host, int port, final PipelineInitializer pipeliner) {
    ServerBootstrap bootsrap = new ServerBootstrap();
    bootsrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override//from   w ww.j a  v a 2s  . co m
                public void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    try {
                        pipeliner.init(pipeline);
                    } catch (Throwable th) {
                        LOG.error("Severe error during pipeline creation", th);
                        throw th;
                    }
                }
            }).option(ChannelOption.SO_BACKLOG, 128).option(ChannelOption.SO_REUSEADDR, true)
            .option(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true);
    try {
        // Bind and start to accept incoming connections.
        ChannelFuture future = bootsrap.bind(host, port);
        LOG.info("Server binded host: {}, port: {}", host, port);
        future.sync();
    } catch (InterruptedException ex) {
        LOG.error(null, ex);
    }
}

From source file:com.grillecube.client.network.ClientNetwork.java

public void start(String host, int port) throws Exception {
    this.workerGroup = new NioEventLoopGroup();
    this.bootstrap = new Bootstrap(); // (1)
    this.bootstrap.group(this.workerGroup); // (2)
    this.bootstrap.channel(NioSocketChannel.class); // (3)
    this.bootstrap.option(ChannelOption.SO_KEEPALIVE, true); // (4)
    this.bootstrap.handler(new ChannelInitializer<SocketChannel>() {
        @Override/*from w w w .j  a v a  2s  . c  o m*/
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(new TimeClientHandler());
        }
    });

    // Start the client.
    try {
        this.channel = this.bootstrap.connect(host, port).sync(); // (5)
    } catch (Exception exception) {
        // args are: quiettime, timeout, time unit
        this.workerGroup.shutdownGracefully(0, 10, TimeUnit.SECONDS);
        Logger.get().log(Level.ERROR, "Couldnt connect to host: " + host + ":" + port);
        exception.printStackTrace(Logger.get().getPrintStream());

        this.bootstrap = null;
        this.channel = null;
        this.workerGroup = null;
    }
}