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:org.dcache.xrootd.tpc.XrootdTpcClient.java

License:Open Source License

public synchronized void connect(final NioEventLoopGroup group, final List<ChannelHandlerFactory> plugins,
        final TpcSourceReadHandler readHandler) throws InterruptedException {
    Bootstrap b = new Bootstrap();
    b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
            .option(ChannelOption.SO_KEEPALIVE, true).handler(new ChannelInitializer<Channel>() {
                @Override//w  w  w .j  av  a  2  s. c o m
                protected void initChannel(Channel ch) throws Exception {
                    injectHandlers(ch.pipeline(), plugins, readHandler);
                }
            });

    channelFuture = b.connect(info.getSrcHost(), info.getSrcPort()).sync();

    isRunning = true;

    notifyAll();

    sendHandshakeRequest(channelFuture.channel().pipeline().lastContext());

    LOGGER.info("Third-party client started for {}, channel {}. stream {}.", info.getSrc(),
            channelFuture.channel().id(), streamId);
}

From source file:org.eclipse.californium.elements.tcp.TcpClientConnector.java

License:Open Source License

@Override
public synchronized void start() throws IOException {
    if (rawDataChannel == null) {
        throw new IllegalStateException("Cannot start without message handler.");
    }// w w w . j  a  v a  2  s  . co m

    if (workerGroup != null) {
        throw new IllegalStateException("Connector already started");
    }

    workerGroup = new NioEventLoopGroup(numberOfThreads);
    poolMap = new AbstractChannelPoolMap<SocketAddress, ChannelPool>() {

        @Override
        protected ChannelPool newPool(SocketAddress key) {
            Bootstrap bootstrap = new Bootstrap().group(workerGroup).channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE, true).option(ChannelOption.AUTO_READ, true)
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeoutMillis).remoteAddress(key);

            // We multiplex over the same TCP connection, so don't acquire
            // more than one connection per endpoint.
            // TODO: But perhaps we could make it a configurable property.
            if (USE_FIXED_CONNECTION_POOL) {
                return new FixedChannelPool(bootstrap, new MyChannelPoolHandler(key), 1);
            } else {
                return new SimpleChannelPool(bootstrap, new MyChannelPoolHandler(key));
            }
        }
    };
}

From source file:org.eclipse.californium.elements.tcp.TcpServerConnector.java

License:Open Source License

@Override
public synchronized void start() throws IOException {
    if (rawDataChannel == null) {
        throw new IllegalStateException("Cannot start without message handler.");
    }/*from  w  ww  .  j  a  v a  2 s .c o m*/
    if (bossGroup != null) {
        throw new IllegalStateException("Connector already started");
    }
    if (workerGroup != null) {
        throw new IllegalStateException("Connector already started");
    }

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

    ServerBootstrap bootstrap = new ServerBootstrap();
    // server socket 
    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelRegistry()).option(ChannelOption.SO_BACKLOG, 100)
            .option(ChannelOption.AUTO_READ, true).childOption(ChannelOption.SO_KEEPALIVE, true);

    // Start the server.
    ChannelFuture channelFuture = bootstrap.bind(localAddress).syncUninterruptibly();

    if (channelFuture.isSuccess() && 0 == localAddress.getPort()) {
        // replace port with the assigned one
        InetSocketAddress listenAddress = (InetSocketAddress) channelFuture.channel().localAddress();
        effectiveLocalAddress = new InetSocketAddress(localAddress.getAddress(), listenAddress.getPort());
    }
}

From source file:org.elasticsearch.hadoop.http.netty4.Netty4HttpServerTransport.java

License:Apache License

@Override
protected void doStart() {
    this.serverOpenChannels = new Netty4OpenChannelsHandler(logger);

    serverBootstrap = new ServerBootstrap();
    if (blockingServer) {
        serverBootstrap/* ww w.jav  a2  s .c om*/
                .group(new OioEventLoopGroup(workerCount, daemonThreadFactory(settings, "http_server_worker")));
        serverBootstrap.channel(OioServerSocketChannel.class);
    } else {
        serverBootstrap
                .group(new NioEventLoopGroup(workerCount, daemonThreadFactory(settings, "http_server_worker")));
        serverBootstrap.channel(NioServerSocketChannel.class);
    }

    serverBootstrap.childHandler(configureServerChannelHandler());

    serverBootstrap.childOption(ChannelOption.TCP_NODELAY, SETTING_HTTP_TCP_NO_DELAY.get(settings));
    serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, SETTING_HTTP_TCP_KEEP_ALIVE.get(settings));

    final ByteSizeValue tcpSendBufferSize = SETTING_HTTP_TCP_SEND_BUFFER_SIZE.get(settings);
    if (tcpSendBufferSize.bytes() > 0) {
        serverBootstrap.childOption(ChannelOption.SO_SNDBUF, Math.toIntExact(tcpSendBufferSize.bytes()));
    }

    final ByteSizeValue tcpReceiveBufferSize = SETTING_HTTP_TCP_RECEIVE_BUFFER_SIZE.get(settings);
    if (tcpReceiveBufferSize.bytes() > 0) {
        serverBootstrap.childOption(ChannelOption.SO_RCVBUF, Math.toIntExact(tcpReceiveBufferSize.bytes()));
    }

    serverBootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, recvByteBufAllocator);
    serverBootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, recvByteBufAllocator);

    final boolean reuseAddress = SETTING_HTTP_TCP_REUSE_ADDRESS.get(settings);
    serverBootstrap.option(ChannelOption.SO_REUSEADDR, reuseAddress);
    serverBootstrap.childOption(ChannelOption.SO_REUSEADDR, reuseAddress);

    this.boundAddress = createBoundHttpAddress();
}

From source file:org.elasticsearch.hadoop.transport.netty4.Netty4Transport.java

License:Apache License

private Bootstrap createBootstrap() {
    final Bootstrap bootstrap = new Bootstrap();
    if (TCP_BLOCKING_CLIENT.get(settings)) {
        bootstrap.group(new OioEventLoopGroup(1,
                daemonThreadFactory(settings, TRANSPORT_CLIENT_WORKER_THREAD_NAME_PREFIX)));
        bootstrap.channel(OioSocketChannel.class);
    } else {/*  w w w  . j  a  v  a 2 s  . c  o m*/
        bootstrap.group(new NioEventLoopGroup(workerCount,
                daemonThreadFactory(settings, TRANSPORT_CLIENT_BOSS_THREAD_NAME_PREFIX)));
        bootstrap.channel(NioSocketChannel.class);
    }

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

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast("size", new Netty4SizeHeaderFrameDecoder());
            // using a dot as a prefix means this cannot come from any settings parsed
            ch.pipeline().addLast("dispatcher",
                    new Netty4MessageChannelHandler(Netty4Transport.this, ".client"));
        }

    });

    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, Math.toIntExact(connectTimeout.millis()));
    bootstrap.option(ChannelOption.TCP_NODELAY, TCP_NO_DELAY.get(settings));
    bootstrap.option(ChannelOption.SO_KEEPALIVE, TCP_KEEP_ALIVE.get(settings));

    final ByteSizeValue tcpSendBufferSize = TCP_SEND_BUFFER_SIZE.get(settings);
    if (tcpSendBufferSize.bytes() > 0) {
        bootstrap.option(ChannelOption.SO_SNDBUF, Math.toIntExact(tcpSendBufferSize.bytes()));
    }

    final ByteSizeValue tcpReceiveBufferSize = TCP_RECEIVE_BUFFER_SIZE.get(settings);
    if (tcpReceiveBufferSize.bytes() > 0) {
        bootstrap.option(ChannelOption.SO_RCVBUF, Math.toIntExact(tcpReceiveBufferSize.bytes()));
    }

    bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, recvByteBufAllocator);

    final boolean reuseAddress = TCP_REUSE_ADDRESS.get(settings);
    bootstrap.option(ChannelOption.SO_REUSEADDR, reuseAddress);

    bootstrap.validate();

    return bootstrap;
}

From source file:org.elasticsearch.hadoop.transport.netty4.Netty4Transport.java

License:Apache License

private void createServerBootstrap(String name, Settings settings) {
    if (logger.isDebugEnabled()) {
        logger.debug(/*from   w ww.  j  a v  a 2 s  .c om*/
                "using profile[{}], worker_count[{}], port[{}], bind_host[{}], publish_host[{}], compress[{}], "
                        + "connect_timeout[{}], connections_per_node[{}/{}/{}/{}/{}], receive_predictor[{}->{}]",
                name, workerCount, settings.get("port"), settings.get("bind_host"),
                settings.get("publish_host"), compress, connectTimeout, connectionsPerNodeRecovery,
                connectionsPerNodeBulk, connectionsPerNodeReg, connectionsPerNodeState, connectionsPerNodePing,
                receivePredictorMin, receivePredictorMax);
    }

    final ThreadFactory workerFactory = daemonThreadFactory(this.settings,
            HTTP_SERVER_WORKER_THREAD_NAME_PREFIX, name);

    final ServerBootstrap serverBootstrap = new ServerBootstrap();

    if (TCP_BLOCKING_SERVER.get(settings)) {
        serverBootstrap.group(new OioEventLoopGroup(workerCount, workerFactory));
        serverBootstrap.channel(OioServerSocketChannel.class);
    } else {
        serverBootstrap.group(new NioEventLoopGroup(workerCount, workerFactory));
        serverBootstrap.channel(NioServerSocketChannel.class);
    }

    serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast("open_channels", Netty4Transport.this.serverOpenChannels);
            ch.pipeline().addLast("size", new Netty4SizeHeaderFrameDecoder());
            ch.pipeline().addLast("dispatcher", new Netty4MessageChannelHandler(Netty4Transport.this, name));
        }
    });

    serverBootstrap.childOption(ChannelOption.TCP_NODELAY, TCP_NO_DELAY.get(settings));
    serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, TCP_KEEP_ALIVE.get(settings));

    final ByteSizeValue tcpSendBufferSize = TCP_SEND_BUFFER_SIZE.getDefault(settings);
    if (tcpSendBufferSize != null && tcpSendBufferSize.bytes() > 0) {
        serverBootstrap.childOption(ChannelOption.SO_SNDBUF, Math.toIntExact(tcpSendBufferSize.bytes()));
    }

    final ByteSizeValue tcpReceiveBufferSize = TCP_RECEIVE_BUFFER_SIZE.getDefault(settings);
    if (tcpReceiveBufferSize != null && tcpReceiveBufferSize.bytes() > 0) {
        serverBootstrap.childOption(ChannelOption.SO_RCVBUF,
                Math.toIntExact(tcpReceiveBufferSize.bytesAsInt()));
    }

    serverBootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, recvByteBufAllocator);
    serverBootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, recvByteBufAllocator);

    final boolean reuseAddress = TCP_REUSE_ADDRESS.get(settings);
    serverBootstrap.option(ChannelOption.SO_REUSEADDR, reuseAddress);
    serverBootstrap.childOption(ChannelOption.SO_REUSEADDR, reuseAddress);

    serverBootstrap.validate();

    serverBootstraps.put(name, serverBootstrap);
}

From source file:org.elasticsearch.http.netty4.Netty4HttpServerTransport.java

License:Apache License

@Override
protected void doStart() {
    this.serverOpenChannels = new Netty4OpenChannelsHandler(logger);

    serverBootstrap = new ServerBootstrap();
    if (blockingServer) {
        serverBootstrap.group(new OioEventLoopGroup(workerCount,
                daemonThreadFactory(settings, HTTP_SERVER_WORKER_THREAD_NAME_PREFIX)));
        serverBootstrap.channel(OioServerSocketChannel.class);
    } else {//from   w ww. ja v  a 2  s  .c  o m
        serverBootstrap.group(new NioEventLoopGroup(workerCount,
                daemonThreadFactory(settings, HTTP_SERVER_WORKER_THREAD_NAME_PREFIX)));
        serverBootstrap.channel(NioServerSocketChannel.class);
    }

    serverBootstrap.childHandler(configureServerChannelHandler());

    serverBootstrap.childOption(ChannelOption.TCP_NODELAY, SETTING_HTTP_TCP_NO_DELAY.get(settings));
    serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, SETTING_HTTP_TCP_KEEP_ALIVE.get(settings));

    final ByteSizeValue tcpSendBufferSize = SETTING_HTTP_TCP_SEND_BUFFER_SIZE.get(settings);
    if (tcpSendBufferSize.bytes() > 0) {
        serverBootstrap.childOption(ChannelOption.SO_SNDBUF, Math.toIntExact(tcpSendBufferSize.bytes()));
    }

    final ByteSizeValue tcpReceiveBufferSize = SETTING_HTTP_TCP_RECEIVE_BUFFER_SIZE.get(settings);
    if (tcpReceiveBufferSize.bytes() > 0) {
        serverBootstrap.childOption(ChannelOption.SO_RCVBUF, Math.toIntExact(tcpReceiveBufferSize.bytes()));
    }

    serverBootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, recvByteBufAllocator);
    serverBootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, recvByteBufAllocator);

    final boolean reuseAddress = SETTING_HTTP_TCP_REUSE_ADDRESS.get(settings);
    serverBootstrap.option(ChannelOption.SO_REUSEADDR, reuseAddress);
    serverBootstrap.childOption(ChannelOption.SO_REUSEADDR, reuseAddress);

    this.boundAddress = createBoundHttpAddress();
}

From source file:org.elasticsearch.transport.netty4.Netty4Transport.java

License:Apache License

private Bootstrap createBootstrap() {
    final Bootstrap bootstrap = new Bootstrap();
    if (TCP_BLOCKING_CLIENT.get(settings)) {
        bootstrap.group(new OioEventLoopGroup(1,
                daemonThreadFactory(settings, TRANSPORT_CLIENT_WORKER_THREAD_NAME_PREFIX)));
        bootstrap.channel(OioSocketChannel.class);
    } else {/*  w  w  w . j  av  a  2 s  . c  o  m*/
        bootstrap.group(new NioEventLoopGroup(workerCount,
                daemonThreadFactory(settings, TRANSPORT_CLIENT_BOSS_THREAD_NAME_PREFIX)));
        bootstrap.channel(NioSocketChannel.class);
    }

    bootstrap.handler(getClientChannelInitializer());

    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, Math.toIntExact(connectTimeout.millis()));
    bootstrap.option(ChannelOption.TCP_NODELAY, TCP_NO_DELAY.get(settings));
    bootstrap.option(ChannelOption.SO_KEEPALIVE, TCP_KEEP_ALIVE.get(settings));

    final ByteSizeValue tcpSendBufferSize = TCP_SEND_BUFFER_SIZE.get(settings);
    if (tcpSendBufferSize.bytes() > 0) {
        bootstrap.option(ChannelOption.SO_SNDBUF, Math.toIntExact(tcpSendBufferSize.bytes()));
    }

    final ByteSizeValue tcpReceiveBufferSize = TCP_RECEIVE_BUFFER_SIZE.get(settings);
    if (tcpReceiveBufferSize.bytes() > 0) {
        bootstrap.option(ChannelOption.SO_RCVBUF, Math.toIntExact(tcpReceiveBufferSize.bytes()));
    }

    bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, recvByteBufAllocator);

    final boolean reuseAddress = TCP_REUSE_ADDRESS.get(settings);
    bootstrap.option(ChannelOption.SO_REUSEADDR, reuseAddress);

    bootstrap.validate();

    return bootstrap;
}

From source file:org.elasticsearch.transport.netty4.Netty4Transport.java

License:Apache License

private void createServerBootstrap(String name, Settings settings) {
    if (logger.isDebugEnabled()) {
        logger.debug(//  ww w .j av  a2  s .  co  m
                "using profile[{}], worker_count[{}], port[{}], bind_host[{}], publish_host[{}], compress[{}], "
                        + "connect_timeout[{}], connections_per_node[{}/{}/{}/{}/{}], receive_predictor[{}->{}]",
                name, workerCount, settings.get("port"), settings.get("bind_host"),
                settings.get("publish_host"), compress, connectTimeout, connectionsPerNodeRecovery,
                connectionsPerNodeBulk, connectionsPerNodeReg, connectionsPerNodeState, connectionsPerNodePing,
                receivePredictorMin, receivePredictorMax);
    }

    final ThreadFactory workerFactory = daemonThreadFactory(this.settings,
            TRANSPORT_SERVER_WORKER_THREAD_NAME_PREFIX, name);

    final ServerBootstrap serverBootstrap = new ServerBootstrap();

    if (TCP_BLOCKING_SERVER.get(settings)) {
        serverBootstrap.group(new OioEventLoopGroup(workerCount, workerFactory));
        serverBootstrap.channel(OioServerSocketChannel.class);
    } else {
        serverBootstrap.group(new NioEventLoopGroup(workerCount, workerFactory));
        serverBootstrap.channel(NioServerSocketChannel.class);
    }

    serverBootstrap.childHandler(getServerChannelInitializer(name, settings));

    serverBootstrap.childOption(ChannelOption.TCP_NODELAY, TCP_NO_DELAY.get(settings));
    serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, TCP_KEEP_ALIVE.get(settings));

    final ByteSizeValue tcpSendBufferSize = TCP_SEND_BUFFER_SIZE.getDefault(settings);
    if (tcpSendBufferSize != null && tcpSendBufferSize.bytes() > 0) {
        serverBootstrap.childOption(ChannelOption.SO_SNDBUF, Math.toIntExact(tcpSendBufferSize.bytes()));
    }

    final ByteSizeValue tcpReceiveBufferSize = TCP_RECEIVE_BUFFER_SIZE.getDefault(settings);
    if (tcpReceiveBufferSize != null && tcpReceiveBufferSize.bytes() > 0) {
        serverBootstrap.childOption(ChannelOption.SO_RCVBUF,
                Math.toIntExact(tcpReceiveBufferSize.bytesAsInt()));
    }

    serverBootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, recvByteBufAllocator);
    serverBootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, recvByteBufAllocator);

    final boolean reuseAddress = TCP_REUSE_ADDRESS.get(settings);
    serverBootstrap.option(ChannelOption.SO_REUSEADDR, reuseAddress);
    serverBootstrap.childOption(ChannelOption.SO_REUSEADDR, reuseAddress);

    serverBootstrap.validate();

    serverBootstraps.put(name, serverBootstrap);
}

From source file:org.ensembl.gti.seqstore.server.MetaDataServer.java

License:Apache License

public void run() throws Exception {
    log.info("Starting server");
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {//from w w  w.ja  va 2  s  .c o  m
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4),
                                getHandler());
                    }
                }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);

        // Bind and start to accept incoming connections.
        log.info("Binding to port " + port);
        ChannelFuture f = b.bind(port).sync();

        // 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.
        log.info("Syncing future");
        f.channel().closeFuture().sync();
    } finally {
        log.info("Shutting server server");
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}