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.apache.spark.network.netty.FileClient.java

License:Apache License

public void init() {
    group = new OioEventLoopGroup();
    bootstrap = new Bootstrap();
    bootstrap.group(group).channel(OioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.TCP_NODELAY, true)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout)
            .handler(new FileClientChannelInitializer(handler));
}

From source file:org.apache.spark.network.netty.NettyTransportClientFactory.java

License:Apache License

/** Create a completely new {@link TransportClient} to the remote address. */
private NettyTransportClient 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<NettyTransportClient> clientRef = new AtomicReference<NettyTransportClient>();
    final AtomicReference<Channel> channelRef = new AtomicReference<Channel>();

    bootstrap.handler(new ChannelInitializer<SocketChannel>() {
        @Override/* w w w.  java2s.com*/
        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());
    }

    NettyTransportClient 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:org.apache.spark.sql.hive.thriftserver.rsc.Rpc.java

License:Apache License

/**
 * Creates an RPC client for a server running on the given remote host and port.
 *
 * @param config RPC configuration data.
 * @param eloop Event loop for managing the connection.
 * @param host Host name or IP address to connect to.
 * @param port Port where server is listening.
 * @param clientId The client ID that identifies the connection.
 * @param secret Secret for authenticating the client with the server.
 * @param dispatcher Dispatcher used to handle RPC calls.
 * @return A future that can be used to monitor the creation of the RPC object.
 *///from ww  w .j av a 2s .  c o  m
public static Promise<Rpc> createClient(final RSCConf config, final EventLoopGroup eloop, String host, int port,
        final String clientId, final String secret, final RpcDispatcher dispatcher) throws Exception {
    int connectTimeoutMs = (int) config.getTimeAsMs(RSCConf.Entry.RPC_CLIENT_CONNECT_TIMEOUT);

    final ChannelFuture cf = new Bootstrap().group(eloop).handler(new ChannelInboundHandlerAdapter() {
    }).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeoutMs).connect(host, port);

    final Promise<Rpc> promise = eloop.next().newPromise();
    final AtomicReference<Rpc> rpc = new AtomicReference<Rpc>();

    // Set up a timeout to undo everything.
    final Runnable timeoutTask = new Runnable() {
        @Override
        public void run() {
            promise.setFailure(new TimeoutException("Timed out waiting for RPC server connection."));
        }
    };
    final ScheduledFuture<?> timeoutFuture = eloop.schedule(timeoutTask,
            config.getTimeAsMs(RSCConf.Entry.RPC_CLIENT_HANDSHAKE_TIMEOUT), TimeUnit.MILLISECONDS);

    // The channel listener instantiates the Rpc instance when the connection is established,
    // and initiates the SASL handshake.
    cf.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture cf) throws Exception {
            if (cf.isSuccess()) {
                SaslClientHandler saslHandler = new SaslClientHandler(config, clientId, promise, timeoutFuture,
                        secret, dispatcher);
                Rpc rpc = createRpc(config, saslHandler, (SocketChannel) cf.channel(), eloop);
                saslHandler.rpc = rpc;
                saslHandler.sendHello(cf.channel());
            } else {
                promise.setFailure(cf.cause());
            }
        }
    });

    // Handle cancellation of the promise.
    promise.addListener(new GenericFutureListener<Promise<Rpc>>() {
        @Override
        public void operationComplete(Promise<Rpc> p) {
            if (p.isCancelled()) {
                cf.cancel(true);
            }
        }
    });

    return promise;
}

From source file:org.apache.spark.sql.hive.thriftserver.rsc.RpcServer.java

License:Apache License

public RpcServer(RSCConf lconf) throws IOException, InterruptedException {
    this.config = lconf;
    this.group = new NioEventLoopGroup(this.config.getInt(RSCConf.Entry.RPC_MAX_THREADS),
            Utils.newDaemonThreadFactory("RPC-Handler-%d"));
    this.channel = new ServerBootstrap().group(group).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override//w w w  .java 2 s. co  m
                public void initChannel(SocketChannel ch) throws Exception {
                    SaslServerHandler saslHandler = new SaslServerHandler(config);
                    final Rpc newRpc = Rpc.createServer(saslHandler, config, ch, group);
                    saslHandler.rpc = newRpc;

                    Runnable cancelTask = new Runnable() {
                        @Override
                        public void run() {
                            LOG.warn("Timed out waiting for hello from client.");
                            newRpc.close();
                        }
                    };
                    saslHandler.cancelTask = group.schedule(cancelTask,
                            config.getTimeAsMs(RSCConf.Entry.RPC_CLIENT_HANDSHAKE_TIMEOUT),
                            TimeUnit.MILLISECONDS);
                }
            }).option(ChannelOption.SO_BACKLOG, 1).option(ChannelOption.SO_REUSEADDR, true)
            .childOption(ChannelOption.SO_KEEPALIVE, true).bind(0).sync().channel();
    this.port = ((InetSocketAddress) channel.localAddress()).getPort();
    this.pendingClients = new ConcurrentHashMap<>();

    String address = config.get(RSCConf.Entry.RPC_SERVER_ADDRESS);
    if (address == null) {
        address = config.findLocalAddress();
    }
    this.address = address;
}

From source file:org.atmosphere.nettosphere.Nettosphere.java

License:Apache License

private void configureBootstrap(ServerBootstrap bootstrap, Config config) {
    bootstrap.childOption(ChannelOption.TCP_NODELAY, config.socketNoTcpDelay());
    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, config.socketKeepAlive());
}

From source file:org.ballerinalang.test.util.http2.HTTP2Client.java

License:Open Source License

public HTTP2Client(boolean ssl, String host, int port) throws Exception {
    try {/*from   w w  w. j  ava 2s  .  c o m*/
        final SslContext sslCtx;
        if (ssl) {
            SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;
            sslCtx = SslContextBuilder.forClient().sslProvider(provider)
                    .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;
        }
        workerGroup = new NioEventLoopGroup();
        HTTP2ClientInitializer initializer = new HTTP2ClientInitializer(sslCtx, Integer.MAX_VALUE);

        // 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 = b.connect().syncUninterruptibly().channel();
        log.info("Connected to [" + host + ':' + port + ']');

        // Wait for the HTTP/2 upgrade to occur.
        HTTP2SettingsHandler http2SettingsHandler = initializer.settingsHandler();
        http2SettingsHandler.awaitSettings(TestConstant.HTTP2_RESPONSE_TIME_OUT,
                TestConstant.HTTP2_RESPONSE_TIME_UNIT);
        responseHandler = initializer.responseHandler();
        scheme = ssl ? HttpScheme.HTTPS : HttpScheme.HTTP;
        hostName = new AsciiString(host + ':' + port);
    } catch (Exception ex) {
        log.error("Error while initializing http2 client " + ex);
        this.close();
    }
}

From source file:org.bermuda.cartilage.core.Connection.java

License:Apache License

public void connect() {
    Bootstrap bootstrap = new Bootstrap().group(new NioEventLoopGroup()).channel(NioSocketChannel.class)
            .option(ChannelOption.SO_KEEPALIVE, true).handler(new ChannelInitializer<SocketChannel>() {
                @Override/*w  w  w  .ja v  a  2s .  c o m*/
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new PacketEncoder(), new ConnectionController());
                }
            });
    try {
        cf = bootstrap.connect("127.0.0.1", 8080).sync();
        cf.addListener(future -> {
            if (future.isSuccess()) {
                System.out.println("Connection successful");
            }
        });
    } catch (InterruptedException ex) {
        ex.printStackTrace();
    }
}

From source file:org.cane.rpc.server.NettyRpcServer.java

License:Open Source License

@Override
public void start() {
    bossGroup = new NioEventLoopGroup();
    workGroup = new NioEventLoopGroup();
    try {/* w w w .  jav  a 2s. c om*/
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workGroup);
        serverBootstrap.channel(NioServerSocketChannel.class);
        serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel channel) throws Exception {
                channel.pipeline().addLast();
            }
        });
        serverBootstrap.option(ChannelOption.SO_BACKLOG, 128);
        serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
        String[] hostAndPort = serverAddress.split(":");

        ChannelFuture future = serverBootstrap.bind(hostAndPort[0], Integer.parseInt(hostAndPort[1])).sync();

        if (serviceRegistry != null) {
            serviceRegistry.registerServer(serverAddress);
        }

        future.channel().closeFuture().sync();
    } catch (Exception e) {
        LOG.error("Init rpc server error!", e);
    }
}

From source file:org.dcache.pool.movers.NettyTransferService.java

License:Open Source License

/**
 * Start netty server.//from   w w  w. j  av  a 2  s  .c om
 *
 * @throws IOException Starting the server failed
 */
protected synchronized void startServer() throws IOException {
    if (serverChannel == null) {
        ServerBootstrap bootstrap = new ServerBootstrap().group(acceptGroup, socketGroup)
                .channel(NioServerSocketChannel.class).childOption(ChannelOption.TCP_NODELAY, false)
                .childOption(ChannelOption.SO_KEEPALIVE, true).childHandler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        NettyTransferService.this.initChannel(ch);
                        ChannelCdcSessionHandlerWrapper.bindSessionToChannel(ch,
                                "pool:" + address + ":" + name + ":" + ch.id());
                    }
                });

        serverChannel = portRange.bind(bootstrap);
        lastServerAddress = (InetSocketAddress) serverChannel.localAddress();
        LOGGER.debug("Started {} on {}", getClass().getSimpleName(), lastServerAddress);
    }
}

From source file:org.dcache.xrootd.standalone.DataServer.java

License:Open Source License

public void start() throws InterruptedException {
    final EventLoopGroup bossGroup;
    final EventLoopGroup workerGroup;
    Class<? extends ServerSocketChannel> channelClass;
    if (_configuration.useBlockingIo) {
        bossGroup = new OioEventLoopGroup();
        workerGroup = new OioEventLoopGroup();
        channelClass = OioServerSocketChannel.class;
    } else {/* ww  w  .j a  va 2 s. co m*/
        bossGroup = new NioEventLoopGroup();
        workerGroup = new NioEventLoopGroup();
        channelClass = NioServerSocketChannel.class;
    }
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            // Shut down all event loops to terminate all threads.
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();

            try {
                // Wait until all threads are terminated.
                bossGroup.terminationFuture().sync();
                workerGroup.terminationFuture().sync();
            } catch (InterruptedException ignored) {
            }
        }
    });
    ServerBootstrap bootstrap = new ServerBootstrap().group(bossGroup, workerGroup).channel(channelClass)
            .localAddress(_configuration.port).childOption(ChannelOption.TCP_NODELAY, true)
            .childOption(ChannelOption.SO_KEEPALIVE, true)
            .childHandler(new DataServerChannelInitializer(_configuration));

    bootstrap.bind().sync().channel().closeFuture().sync();
}