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:cf.dropsonde.firehose.NettyFirehoseOnSubscribe.java

License:Open Source License

public NettyFirehoseOnSubscribe(URI uri, String token, String subscriptionId, boolean skipTlsValidation,
        EventLoopGroup eventLoopGroup, Class<? extends SocketChannel> channelClass) {
    try {/*from   w w w  .  j  a v  a2 s .  co m*/
        final String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
        final String scheme = uri.getScheme() == null ? "ws" : uri.getScheme();
        final int port = getPort(scheme, uri.getPort());
        final URI fullUri = uri.resolve("/firehose/" + subscriptionId);

        final SslContext sslContext;
        if ("wss".equalsIgnoreCase(scheme)) {
            final SslContextBuilder sslContextBuilder = SslContextBuilder.forClient();
            if (skipTlsValidation) {
                sslContextBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE);
            } else {
                TrustManagerFactory trustManagerFactory = TrustManagerFactory
                        .getInstance(TrustManagerFactory.getDefaultAlgorithm());
                trustManagerFactory.init((KeyStore) null);
                sslContextBuilder.trustManager(trustManagerFactory);
            }
            sslContext = sslContextBuilder.build();
        } else {
            sslContext = null;
        }

        bootstrap = new Bootstrap();
        if (eventLoopGroup == null) {
            this.eventLoopGroup = new NioEventLoopGroup();
            bootstrap.group(this.eventLoopGroup);
        } else {
            this.eventLoopGroup = null;
            bootstrap.group(eventLoopGroup);
        }
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 15000)
                .channel(channelClass == null ? NioSocketChannel.class : channelClass).remoteAddress(host, port)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel c) throws Exception {
                        final HttpHeaders headers = new DefaultHttpHeaders();
                        headers.add(HttpHeaders.Names.AUTHORIZATION, token);
                        final WebSocketClientHandler handler = new WebSocketClientHandler(
                                WebSocketClientHandshakerFactory.newHandshaker(fullUri, WebSocketVersion.V13,
                                        null, false, headers));
                        final ChannelPipeline pipeline = c.pipeline();
                        if (sslContext != null) {
                            pipeline.addLast(sslContext.newHandler(c.alloc(), host, port));
                        }
                        pipeline.addLast(new ReadTimeoutHandler(30));
                        pipeline.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192));
                        pipeline.addLast(HANDLER_NAME, handler);

                        channel = c;
                    }
                });
    } catch (NoSuchAlgorithmException | SSLException | KeyStoreException e) {
        throw new RuntimeException(e);
    }
}

From source file:cn.david.socks.SocksServerConnectHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception {
    Promise<Channel> promise = ctx.executor().newPromise();
    promise.addListener(new GenericFutureListener<Future<Channel>>() {
        @Override/*from  w ww  . j  av a2 s  .  com*/
        public void operationComplete(final Future<Channel> future) throws Exception {
            final Channel outboundChannel = future.getNow();
            if (future.isSuccess()) {
                ctx.channel().writeAndFlush(new SocksCmdResponse(SocksCmdStatus.SUCCESS, request.addressType()))
                        .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 SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                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.host(), request.port()).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 SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                SocksServerUtils.closeOnFlush(ctx.channel());
            }
        }
    });
}

From source file:code.google.nfs.rpc.netty.client.NettyClientFactory.java

License:Apache License

protected Client createClient(String targetIP, int targetPort, int connectTimeout, String key)
        throws Exception {
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(workerGroup).channel(NioSocketChannel.class)
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .option(ChannelOption.TCP_NODELAY,
                    Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.nodelay", "true")))
            .option(ChannelOption.SO_REUSEADDR,
                    Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.reuseaddress", "true")));
    if (connectTimeout < 1000) {
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000);
    } else {//ww w.  j  a va2s  .c  o m
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout);
    }
    final NettyClientHandler handler = new NettyClientHandler(this, key);
    bootstrap.handler(new ChannelInitializer<SocketChannel>() {

        protected void initChannel(SocketChannel channel) throws Exception {
            ChannelPipeline pipeline = channel.pipeline();
            pipeline.addLast("decoder", new NettyProtocolDecoder());
            pipeline.addLast("encoder", new NettyProtocolEncoder());
            pipeline.addLast("handler", handler);
        }

    });
    ChannelFuture future = bootstrap.connect(new InetSocketAddress(targetIP, targetPort)).sync();
    future.awaitUninterruptibly(connectTimeout);
    if (!future.isDone()) {
        LOGGER.error("Create connection to " + targetIP + ":" + targetPort + " timeout!");
        throw new Exception("Create connection to " + targetIP + ":" + targetPort + " timeout!");
    }
    if (future.isCancelled()) {
        LOGGER.error("Create connection to " + targetIP + ":" + targetPort + " cancelled by user!");
        throw new Exception("Create connection to " + targetIP + ":" + targetPort + " cancelled by user!");
    }
    if (!future.isSuccess()) {
        LOGGER.error("Create connection to " + targetIP + ":" + targetPort + " error", future.cause());
        throw new Exception("Create connection to " + targetIP + ":" + targetPort + " error", future.cause());
    }
    NettyClient client = new NettyClient(future, key, connectTimeout);
    handler.setClient(client);
    return client;
}

From source file:code.google.nfs.rpc.netty4.client.Netty4ClientFactory.java

License:Apache License

protected Client createClient(String targetIP, int targetPort, int connectTimeout, String key)
        throws Exception {
    final Netty4ClientHandler handler = new Netty4ClientHandler(this, key);

    EventLoopGroup group = new NioEventLoopGroup(1);
    Bootstrap b = new Bootstrap();
    b.group(group).channel(NioSocketChannel.class)
            .option(ChannelOption.TCP_NODELAY,
                    Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.nodelay", "true")))
            .option(ChannelOption.SO_REUSEADDR,
                    Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.reuseaddress", "true")))
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout < 1000 ? 1000 : connectTimeout)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override/*w w  w  .  j  a  v a  2  s. c  om*/
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast("decoder", new Netty4ProtocolDecoder());
                    ch.pipeline().addLast("encoder", new Netty4ProtocolEncoder());
                    ch.pipeline().addLast("handler", handler);
                }
            });

    ChannelFuture future = b.connect(targetIP, targetPort);

    future.awaitUninterruptibly(connectTimeout);
    if (!future.isDone()) {
        LOGGER.error("Create connection to " + targetIP + ":" + targetPort + " timeout!");
        throw new Exception("Create connection to " + targetIP + ":" + targetPort + " timeout!");
    }
    if (future.isCancelled()) {
        LOGGER.error("Create connection to " + targetIP + ":" + targetPort + " cancelled by user!");
        throw new Exception("Create connection to " + targetIP + ":" + targetPort + " cancelled by user!");
    }
    if (!future.isSuccess()) {
        LOGGER.error("Create connection to " + targetIP + ":" + targetPort + " error", future.cause());
        throw new Exception("Create connection to " + targetIP + ":" + targetPort + " error", future.cause());
    }
    Netty4Client client = new Netty4Client(future, key, connectTimeout);
    handler.setClient(client);
    return client;
}

From source file:com.addthis.meshy.Meshy.java

License:Apache License

protected Meshy() {
    if (HOSTNAME != null) {
        uuid = HOSTNAME + "-" + Long.toHexString(System.currentTimeMillis() & 0xffffff);
    } else {//  w  w  w.j av  a2 s. c om
        uuid = Long.toHexString(UUID.randomUUID().getMostSignificantBits());
    }
    workerGroup = new NioEventLoopGroup();
    clientBootstrap = new Bootstrap().option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 30000)
            .option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, HIGH_WATERMARK)
            .option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, LOW_WATERMARK).channel(NioSocketChannel.class)
            .group(workerGroup).handler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(final NioSocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new ChannelState(Meshy.this, ch));
                }
            });
    updateLastEventTime();
}

From source file:com.addthis.meshy.MeshyServer.java

License:Apache License

public MeshyServer(final int port, final File rootDir, @Nullable String[] netif, final MeshyServerGroup group)
        throws IOException {
    super();//from   w ww.j  a v a2  s .  c om
    this.group = group;
    this.rootDir = rootDir;
    this.filesystems = loadFileSystems(rootDir);
    this.serverPeers = new AtomicInteger(0);
    bossGroup = new NioEventLoopGroup(1);
    ServerBootstrap bootstrap = new ServerBootstrap()
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .option(ChannelOption.SO_BACKLOG, 1024).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 30000)
            .option(ChannelOption.SO_REUSEADDR, true)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true)
            .childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, HIGH_WATERMARK)
            .childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, LOW_WATERMARK)
            .channel(NioServerSocketChannel.class).group(bossGroup, workerGroup)
            .childHandler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(final NioSocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new ChannelState(MeshyServer.this, ch));
                }
            });
    /* bind to one or more interfaces, if supplied, otherwise all */
    if ((netif == null) || (netif.length == 0)) {
        ServerSocketChannel serverChannel = (ServerSocketChannel) bootstrap.bind(new InetSocketAddress(port))
                .syncUninterruptibly().channel();
        serverLocal = serverChannel.localAddress();
    } else {
        InetSocketAddress primaryServerLocal = null;
        for (String net : netif) {
            NetworkInterface nicif = NetworkInterface.getByName(net);
            if (nicif == null) {
                log.warn("missing speficied NIC: {}", net);
                continue;
            }
            for (InterfaceAddress addr : nicif.getInterfaceAddresses()) {
                InetAddress inAddr = addr.getAddress();
                if (inAddr.getAddress().length != 4) {
                    log.trace("skip non-ipV4 address: {}", inAddr);
                    continue;
                }
                ServerSocketChannel serverChannel = (ServerSocketChannel) bootstrap
                        .bind(new InetSocketAddress(inAddr, port)).syncUninterruptibly().channel();
                if (primaryServerLocal != null) {
                    log.info("server [{}-*] binding to extra address: {}", super.getUUID(), primaryServerLocal);
                }
                primaryServerLocal = serverChannel.localAddress();
            }
        }
        if (primaryServerLocal == null) {
            throw new IllegalArgumentException("no valid interface / port specified");
        }
        serverLocal = primaryServerLocal;
    }
    this.serverNetIf = NetworkInterface.getByInetAddress(serverLocal.getAddress());
    this.serverPort = serverLocal.getPort();
    if (serverNetIf != null) {
        serverUuid = super.getUUID() + "-" + serverPort + "-" + serverNetIf.getName();
    } else {
        serverUuid = super.getUUID() + "-" + serverPort;
    }
    log.info("server [{}] on {} @ {}", getUUID(), serverLocal, rootDir);
    closeFuture = new DefaultPromise<>(GlobalEventExecutor.INSTANCE);
    workerGroup.terminationFuture().addListener((Future<Object> workerFuture) -> {
        bossGroup.terminationFuture().addListener((Future<Object> bossFuture) -> {
            if (!workerFuture.isSuccess()) {
                closeFuture.tryFailure(workerFuture.cause());
            } else if (!bossFuture.isSuccess()) {
                closeFuture.tryFailure(bossFuture.cause());
            } else {
                closeFuture.trySuccess(null);
            }
        });
    });
    addMessageFileSystemPaths();
    group.join(this);
    if (autoMesh) {
        startAutoMesh(serverPort, autoMeshTimeout);
    }
}

From source file:com.alibaba.dubbo.remoting.transport.netty.NettyClient.java

License:Apache License

@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    final NettyClientHandler nettyClientHandler = new NettyClientHandler(getUrl(), this);
    bootstrap = new Bootstrap();
    bootstrap.group(nioEventLoopGroup).option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.TCP_NODELAY, true)
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            //.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, getTimeout())
            .channel(NioSocketChannel.class);

    if (getTimeout() < 3000) {
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000);
    } else {//from w  w  w .  j a  va  2 s  .c  o m
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, getTimeout());
    }

    bootstrap.handler(new ChannelInitializer() {

        protected void initChannel(Channel ch) throws Exception {
            NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyClient.this);
            ch.pipeline()//.addLast("logging",new LoggingHandler(LogLevel.INFO))//for debug
                    .addLast("decoder", adapter.getDecoder())//
                    .addLast("encoder", adapter.getEncoder())//
                    .addLast("handler", nettyClientHandler);
        }
    });
}

From source file:com.allanbank.mongodb.netty.NettyTransportFactory.java

License:Apache License

/**
 * Creates a new {@link Bootstrap} for creating a Netty client
 * {@link Channel channels}./*from   w  w  w .  j  av a  2  s.c om*/
 *
 * @param config
 *            The configuration for the client.
 * @return The {@link Bootstrap} to create Netty client channels.
 */
protected Bootstrap createBootstrap(final MongoClientConfiguration config) {
    final Bootstrap bootstrap = new Bootstrap();

    bootstrap.channel(NioSocketChannel.class);
    bootstrap.option(ChannelOption.ALLOCATOR, myBufferAllocator);
    bootstrap.group(myGroup);

    // Suggested defaults.
    bootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
    bootstrap.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);

    // Settings from the config.
    bootstrap.option(ChannelOption.SO_KEEPALIVE, Boolean.valueOf(config.isUsingSoKeepalive()));
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, Integer.valueOf(config.getConnectTimeout()));

    return bootstrap;
}

From source file:com.amazonaws.http.AmazonRxNettyHttpClient.java

License:Apache License

private HttpClient<ByteBuf, ByteBuf> getClient(String host) {
    Protocol protocol = clientConfiguration.getProtocol();
    String key = protocol + "|" + host;
    if (!CLIENTS.containsKey(key)) {
        boolean isSecure;
        int port;
        if (Protocol.HTTP.equals(protocol)) {
            isSecure = false;//w w w  . j a va2s  .co  m
            port = 80;
        } else if (Protocol.HTTPS.equals(protocol)) {
            isSecure = true;
            port = 443;
        } else {
            throw new IllegalStateException("unknown protocol: " + protocol);
        }

        HttpClientConfig config = new HttpClient.HttpClientConfig.Builder().setFollowRedirect(true)
                .readTimeout(clientConfiguration.getSocketTimeout(), TimeUnit.MILLISECONDS)
                .responseSubscriptionTimeout(5000, TimeUnit.MILLISECONDS).build();

        HttpClient<ByteBuf, ByteBuf> client = RxNetty.<ByteBuf, ByteBuf>newHttpClientBuilder(host, port)
                .withName(host + "." + port).config(config)
                .channelOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, clientConfiguration.getConnectionTimeout())
                //.enableWireLogging(io.netty.handler.logging.LogLevel.ERROR)
                .withMaxConnections(clientConfiguration.getMaxConnections())
                .withIdleConnectionsTimeoutMillis(60000)
                .withSslEngineFactory((isSecure) ? DefaultFactories.trustAll() : null)
                .pipelineConfigurator(
                        new PipelineConfiguratorComposite<HttpClientResponse<ByteBuf>, HttpClientRequest<ByteBuf>>(
                                new HttpClientPipelineConfigurator<ByteBuf, ByteBuf>(),
                                new HttpDecompressionConfigurator()))
                .appendPipelineConfigurator(pipeline -> pipeline
                        .addLast(new ActiveLifeTracker(clientConfiguration.getConnectionTTL())))
                .disableAutoReleaseBuffers().build();
        CLIENTS.putIfAbsent(key, client);
    }
    return CLIENTS.get(key);
}

From source file:com.ancun.netty.httpserver.HttpServer.java

License:Apache License

private void setBootstrapOptions(ServerBootstrap bootstrap) {
    bootstrap.option(ChannelOption.SO_KEEPALIVE, useKeepAlive());
    bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
    bootstrap.option(ChannelOption.TCP_NODELAY, useTcpNoDelay());
    bootstrap.option(ChannelOption.SO_KEEPALIVE, serverSettings.isKeepAlive());
    bootstrap.option(ChannelOption.SO_REUSEADDR, shouldReuseAddress());
    bootstrap.option(ChannelOption.SO_LINGER, getSoLinger());
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, getConnectTimeoutMillis());
    bootstrap.option(ChannelOption.SO_RCVBUF, getReceiveBufferSize());
    bootstrap.option(ChannelOption.MAX_MESSAGES_PER_READ, Integer.MAX_VALUE);

    bootstrap.childOption(ChannelOption.ALLOCATOR, new PooledByteBufAllocator(true));
    bootstrap.childOption(ChannelOption.MAX_MESSAGES_PER_READ, Integer.MAX_VALUE);
    bootstrap.childOption(ChannelOption.SO_RCVBUF, getReceiveBufferSize());
    bootstrap.childOption(ChannelOption.SO_REUSEADDR, shouldReuseAddress());
}