Example usage for io.netty.channel ChannelOption CONNECT_TIMEOUT_MILLIS

List of usage examples for io.netty.channel ChannelOption CONNECT_TIMEOUT_MILLIS

Introduction

In this page you can find the example usage for io.netty.channel ChannelOption CONNECT_TIMEOUT_MILLIS.

Prototype

ChannelOption CONNECT_TIMEOUT_MILLIS

To view the source code for io.netty.channel ChannelOption CONNECT_TIMEOUT_MILLIS.

Click Source Link

Usage

From source file:com.cloudera.livy.client.local.rpc.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.
 *//* w  w w .  j a  v a2s  .  com*/
public static Promise<Rpc> createClient(final LocalConf config, final EventLoopGroup eloop, String host,
        int port, final String clientId, final String secret, final RpcDispatcher dispatcher) throws Exception {
    int connectTimeoutMs = (int) config.getTimeAsMs(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(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:com.cloudera.livy.rsc.rpc.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 a v  a2  s  .  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(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(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:com.codebullets.external.party.simulator.connections.websocket.outbound.OutboundWebSocketConnection.java

License:Apache License

/**
 * Open the connection to the target web socket endpoint.
 *///w  ww .  jav a  2s  .  c om
public void openConnection() {
    LOG.info("Connecting to web socket server at {}", targetEndpoint);

    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(eventGroup).channel(NioSocketChannel.class)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT_MILLIS)
            .handler(new WebSocketClientInitializer(monitor, connectionConfig, this));

    bootstrap.connect(targetEndpoint.getHost(), targetEndpoint.getPort())
            .addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(final ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        connectionEstablished(future.channel());
                    } else {
                        LOG.warn("Connection to {} failed: {}", targetEndpoint, future.cause().getMessage());
                        eventGroup.schedule(new Runnable() {
                            @Override
                            public void run() {
                                openConnection();
                            }
                        }, CONNECT_RETRY_DELAY_MILLIS, TimeUnit.MILLISECONDS);
                    }
                }
            });
}

From source file:com.couchbase.client.core.endpoint.AbstractEndpoint.java

License:Apache License

/**
 * Create a new {@link AbstractEndpoint}.
 *
 * @param hostname the hostname/ipaddr of the remote channel.
 * @param bucket the name of the bucket.
 * @param password the password of the bucket.
 * @param port the port of the remote channel.
 * @param environment the environment of the core.
 * @param responseBuffer the response buffer for passing responses up the stack.
 *//*  w  w  w  .  ja va 2s .  c o m*/
protected AbstractEndpoint(final String hostname, final String bucket, final String password, final int port,
        final CoreEnvironment environment, final RingBuffer<ResponseEvent> responseBuffer,
        boolean isTransient) {
    super(LifecycleState.DISCONNECTED);
    this.bucket = bucket;
    this.password = password;
    this.responseBuffer = responseBuffer;
    this.env = environment;
    this.isTransient = isTransient;
    if (environment.sslEnabled()) {
        this.sslEngineFactory = new SSLEngineFactory(environment);
    }

    Class<? extends Channel> channelClass = NioSocketChannel.class;
    if (environment.ioPool() instanceof EpollEventLoopGroup) {
        channelClass = EpollSocketChannel.class;
    } else if (environment.ioPool() instanceof OioEventLoopGroup) {
        channelClass = OioSocketChannel.class;
    }

    ByteBufAllocator allocator = env.bufferPoolingEnabled() ? PooledByteBufAllocator.DEFAULT
            : UnpooledByteBufAllocator.DEFAULT;

    boolean tcpNodelay = environment().tcpNodelayEnabled();
    bootstrap = new BootstrapAdapter(
            new Bootstrap().remoteAddress(hostname, port).group(environment.ioPool()).channel(channelClass)
                    .option(ChannelOption.ALLOCATOR, allocator).option(ChannelOption.TCP_NODELAY, tcpNodelay)
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, env.socketConnectTimeout())
                    .handler(new ChannelInitializer<Channel>() {
                        @Override
                        protected void initChannel(Channel channel) throws Exception {
                            ChannelPipeline pipeline = channel.pipeline();
                            if (environment.sslEnabled()) {
                                pipeline.addLast(new SslHandler(sslEngineFactory.get()));
                            }
                            if (LOGGER.isTraceEnabled()) {
                                pipeline.addLast(LOGGING_HANDLER_INSTANCE);
                            }
                            customEndpointHandlers(pipeline);
                        }
                    }));
}

From source file:com.digitalpetri.modbus.master.ModbusTcpMaster.java

License:Apache License

public static CompletableFuture<Channel> bootstrap(ModbusTcpMaster master, ModbusTcpMasterConfig config) {
    CompletableFuture<Channel> future = new CompletableFuture<>();

    Bootstrap bootstrap = new Bootstrap();

    config.getBootstrapConsumer().accept(bootstrap);

    bootstrap.group(config.getEventLoop()).channel(NioSocketChannel.class)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) config.getTimeout().toMillis())
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override//w  w  w .  j ava  2s  . c  o  m
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(
                            new ModbusTcpCodec(new ModbusRequestEncoder(), new ModbusResponseDecoder()));
                    ch.pipeline().addLast(new ModbusTcpMasterHandler(master));
                }
            }).connect(config.getAddress(), config.getPort()).addListener((ChannelFuture f) -> {
                if (f.isSuccess()) {
                    future.complete(f.channel());
                } else {
                    future.completeExceptionally(f.cause());
                }
            });

    return future;
}

From source file:com.digitalpetri.opcua.stack.client.UaTcpStackClient.java

License:Apache License

public static CompletableFuture<ClientSecureChannel> bootstrap(UaTcpStackClient client,
        Optional<ClientSecureChannel> existingChannel) {

    CompletableFuture<ClientSecureChannel> handshake = new CompletableFuture<>();

    Bootstrap bootstrap = new Bootstrap();

    bootstrap.group(client.getConfig().getEventLoop()).channel(NioSocketChannel.class)
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000).option(ChannelOption.TCP_NODELAY, true)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override/*from  ww  w.j a  v  a 2  s  .co m*/
                protected void initChannel(SocketChannel channel) throws Exception {
                    UaTcpClientAcknowledgeHandler acknowledgeHandler = new UaTcpClientAcknowledgeHandler(client,
                            existingChannel, handshake);

                    channel.pipeline().addLast(acknowledgeHandler);
                }
            });

    try {
        URI uri = URI.create(client.getEndpointUrl());

        bootstrap.connect(uri.getHost(), uri.getPort()).addListener((ChannelFuture f) -> {
            if (!f.isSuccess()) {
                handshake.completeExceptionally(f.cause());
            }
        });
    } catch (Throwable t) {
        UaException failure = new UaException(StatusCodes.Bad_TcpEndpointUrlInvalid,
                "endpoint URL invalid: " + client.getEndpointUrl());

        handshake.completeExceptionally(failure);
    }

    return handshake;
}

From source file:com.dinstone.jrpc.transport.netty4.NettyConnector.java

License:Apache License

public NettyConnector(InetSocketAddress isa, final TransportConfig transportConfig) {
    workerGroup = new NioEventLoopGroup(1, new DefaultThreadFactory("N4C-Work"));
    clientBoot = new Bootstrap().group(workerGroup).channel(NioSocketChannel.class);
    clientBoot.option(ChannelOption.TCP_NODELAY, true);
    clientBoot.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, transportConfig.getConnectTimeout());
    clientBoot.option(ChannelOption.SO_RCVBUF, 8 * 1024).option(ChannelOption.SO_SNDBUF, 8 * 1024);
    clientBoot.handler(new ChannelInitializer<SocketChannel>() {

        @Override/*from   w  w w.jav  a  2 s .c o m*/
        public void initChannel(SocketChannel ch) throws Exception {
            TransportProtocolDecoder decoder = new TransportProtocolDecoder();
            decoder.setMaxObjectSize(transportConfig.getMaxSize());
            TransportProtocolEncoder encoder = new TransportProtocolEncoder();
            encoder.setMaxObjectSize(transportConfig.getMaxSize());
            ch.pipeline().addLast("TransportProtocolDecoder", decoder);
            ch.pipeline().addLast("TransportProtocolEncoder", encoder);

            int intervalSeconds = transportConfig.getHeartbeatIntervalSeconds();
            ch.pipeline().addLast("IdleStateHandler", new IdleStateHandler(0, intervalSeconds, 0));
            ch.pipeline().addLast("NettyClientHandler", new NettyClientHandler());
        }
    });

    clientBoot.remoteAddress(isa);
}

From source file:com.dinstone.jrpc.transport.netty5.NettyConnector.java

License:Apache License

public NettyConnector(InetSocketAddress isa, final TransportConfig transportConfig) {
    workerGroup = new NioEventLoopGroup(1, new DefaultExecutorServiceFactory("N5C-Work"));
    clientBoot = new Bootstrap().group(workerGroup).channel(NioSocketChannel.class);
    clientBoot.option(ChannelOption.TCP_NODELAY, true);
    clientBoot.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, transportConfig.getConnectTimeout());
    clientBoot.option(ChannelOption.SO_RCVBUF, 8 * 1024).option(ChannelOption.SO_SNDBUF, 8 * 1024);
    clientBoot.handler(new ChannelInitializer<SocketChannel>() {

        @Override// www  .  j a  v a2  s .c o  m
        public void initChannel(SocketChannel ch) throws Exception {
            TransportProtocolDecoder decoder = new TransportProtocolDecoder();
            decoder.setMaxObjectSize(transportConfig.getMaxSize());
            TransportProtocolEncoder encoder = new TransportProtocolEncoder();
            encoder.setMaxObjectSize(transportConfig.getMaxSize());
            ch.pipeline().addLast("TransportProtocolDecoder", decoder);
            ch.pipeline().addLast("TransportProtocolEncoder", encoder);

            int intervalSeconds = transportConfig.getHeartbeatIntervalSeconds();
            ch.pipeline().addLast("IdleStateHandler", new IdleStateHandler(0, intervalSeconds, 0));
            ch.pipeline().addLast("NettyClientHandler", new NettyClientHandler());
        }
    });

    clientBoot.remoteAddress(isa);
}

From source file:com.ebay.jetstream.http.netty.client.HttpClient.java

License:MIT License

private void createChannelPipeline() {

    if (isPipelineCreated())
        return;/*w w w . j a  v a2 s .  c o  m*/

    m_workerGroup = new NioEventLoopGroup(getConfig().getNumWorkers(),
            new NameableThreadFactory("Jetstream-HttpClientWorker"));
    m_bootstrap = new Bootstrap();
    m_bootstrap.group(m_workerGroup).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
            .option(ChannelOption.SO_KEEPALIVE, false)
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, getConfig().getConnectionTimeoutInSecs())
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast("timeout",
                            new IdleStateHandler(0, getConfig().getIdleTimeoutInSecs(), 0));
                    ch.pipeline().addLast("decoder", new HttpResponseDecoder());
                    ch.pipeline().addLast("decompressor", new HttpContentDecompressor());
                    ch.pipeline().addLast("encoder", new HttpRequestEncoder());
                    ch.pipeline().addLast("aggregator",
                            new HttpObjectAggregator(m_config.getMaxContentLength()));
                    ch.pipeline().addLast(m_httpRequestHandler);
                }
            });

    if (getConfig().getRvcBufSz() > 0) {
        m_bootstrap.option(ChannelOption.SO_RCVBUF, (int) getConfig().getRvcBufSz());
    }

    if (getConfig().getSendBufSz() > 0) {
        m_bootstrap.option(ChannelOption.SO_SNDBUF, (int) getConfig().getSendBufSz());
    }
    createdPipeline();

}

From source file:com.ebay.jetstream.http.netty.server.Acceptor.java

License:MIT License

/**
 * @param rxSessionHandler/*from  w w  w. j av  a2  s.  c  om*/
 * @throws Exception
 */
public void bind(final HttpRequestHandler httpReqHandler, final HttpServerStatisticsHandler statisticsHandler)
        throws Exception {
    m_bossGroup = new NioEventLoopGroup(1, new NameableThreadFactory("NettyHttpServerAcceptor"));
    m_workerGroup = new NioEventLoopGroup(m_numIoProcessors,
            new NameableThreadFactory("NettyHttpServerWorker"));

    try {
        m_serverbootstrap = new ServerBootstrap();
        m_serverbootstrap.group(m_bossGroup, m_workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast("timeout", new IdleStateHandler((int) m_readIdleTimeout, 0, 0));
                        ch.pipeline().addLast("stats", statisticsHandler);
                        ch.pipeline().addLast("decoder", new HttpRequestDecoder());
                        ch.pipeline().addLast("encoder", new HttpResponseEncoder());
                        ch.pipeline().addLast("decompressor", new HttpContentDecompressor());
                        ch.pipeline().addLast("deflater", new HttpContentCompressor(1));
                        ch.pipeline().addLast("aggregator", new HttpObjectAggregator(m_maxContentLength));
                        if (m_maxKeepAliveRequests > 0 || m_maxKeepAliveTimeout > 0) {
                            ch.pipeline().addLast("keepAliveHandler",
                                    new KeepAliveHandler(m_maxKeepAliveRequests, m_maxKeepAliveTimeout));
                        }
                        ch.pipeline().addLast("handler", httpReqHandler);

                    }

                }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.TCP_NODELAY, true)
                .childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
                .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .childOption(ChannelOption.SO_KEEPALIVE, false);

        if (m_config.getRvcBufSz() > 0) {
            m_serverbootstrap.childOption(ChannelOption.SO_RCVBUF, (int) m_config.getRvcBufSz());
        }

        if (m_config.getSendBufSz() > 0) {
            m_serverbootstrap.childOption(ChannelOption.SO_SNDBUF, (int) m_config.getSendBufSz());
        }

    } catch (Exception t) {
        throw t;
    }

    m_acceptorSocket = new InetSocketAddress(m_ipAddress, m_tcpPort);
    m_serverbootstrap.bind(m_acceptorSocket).sync();

    if (!m_ipAddress.isLoopbackAddress() && !m_ipAddress.isAnyLocalAddress()) {
        // Add lookback if not bind
        m_localAcceptorSocket = new InetSocketAddress("127.0.0.1", m_tcpPort);
        m_serverbootstrap.bind(m_localAcceptorSocket).sync();
    }
}