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:io.atomix.catalyst.transport.NettyClient.java

License:Apache License

@Override
public CompletableFuture<Connection> connect(Address address) {
    Assert.notNull(address, "address");
    ThreadContext context = ThreadContext.currentContextOrThrow();
    CompletableFuture<Connection> future = new ComposableFuture<>();

    LOGGER.info("Connecting to {}", address);

    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(eventLoopGroup).channel(
            eventLoopGroup instanceof EpollEventLoopGroup ? EpollSocketChannel.class : NioSocketChannel.class)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override//from ww w. j  av  a  2  s.c  o  m
                protected void initChannel(SocketChannel channel) throws Exception {
                    ChannelPipeline pipeline = channel.pipeline();
                    pipeline.addLast(FIELD_PREPENDER);
                    pipeline.addLast(new LengthFieldBasedFrameDecoder(1024 * 32, 0, 2, 0, 2));
                    pipeline.addLast(new NettyHandler(connections, future::complete, context));
                }
            });

    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000);
    bootstrap.option(ChannelOption.ALLOCATOR, ALLOCATOR);

    bootstrap.connect(address.socketAddress()).addListener(channelFuture -> {
        if (channelFuture.isSuccess()) {
            LOGGER.info("Connected to {}", address);
        } else {
            context.execute(() -> future.completeExceptionally(channelFuture.cause()));
        }
    });
    return future;
}

From source file:io.atomix.cluster.messaging.impl.NettyMessagingService.java

License:Apache License

private Bootstrap bootstrapClient(Address address) {
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    bootstrap.option(ChannelOption.WRITE_BUFFER_WATER_MARK,
            new WriteBufferWaterMark(10 * 32 * 1024, 10 * 64 * 1024));
    bootstrap.option(ChannelOption.SO_RCVBUF, 1024 * 1024);
    bootstrap.option(ChannelOption.SO_SNDBUF, 1024 * 1024);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000);
    bootstrap.group(clientGroup);/*from  w  w w .  ja v a2 s  .c  o m*/
    // TODO: Make this faster:
    // http://normanmaurer.me/presentations/2014-facebook-eng-netty/slides.html#37.0
    bootstrap.channel(clientChannelClass);
    bootstrap.remoteAddress(address.address(true), address.port());
    if (enableNettyTls) {
        bootstrap.handler(new SslClientCommunicationChannelInitializer());
    } else {
        bootstrap.handler(new BasicChannelInitializer());
    }
    return bootstrap;
}

From source file:io.codis.nedis.NedisClientBuilder.java

License:Apache License

public Future<NedisClientImpl> connect(SocketAddress remoteAddress) {
    validateGroupConfig();/*from  w ww. j a v  a 2 s  .c  o m*/
    Bootstrap b = new Bootstrap().group(group).channel(channelClass).handler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            ch.pipeline().addLast(new RedisResponseDecoder(),
                    new RedisDuplexHandler(TimeUnit.MILLISECONDS.toNanos(timeoutMs)));
        }

    });
    if (timeoutMs > 0) {
        b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) Math.min(Integer.MAX_VALUE, timeoutMs));
    }
    ChannelFuture f = b.connect(remoteAddress);
    final Promise<NedisClientImpl> promise = f.channel().eventLoop().newPromise();
    f.addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                promise.trySuccess(new NedisClientImpl(future.channel(), pool));
            } else {
                promise.tryFailure(future.cause());
            }
        }
    });
    return promise;
}

From source file:io.jsync.net.impl.TCPSSLHelper.java

License:Open Source License

public void applyConnectionOptions(Bootstrap bootstrap) {
    bootstrap.option(ChannelOption.TCP_NODELAY, tcpNoDelay);
    if (tcpSendBufferSize != -1) {
        bootstrap.option(ChannelOption.SO_SNDBUF, tcpSendBufferSize);
    }/*from w  ww  . j av  a 2  s  .  c o  m*/
    if (tcpReceiveBufferSize != -1) {
        bootstrap.option(ChannelOption.SO_RCVBUF, tcpReceiveBufferSize);
        bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(tcpReceiveBufferSize));
    }

    if (soLinger != -1) {
        bootstrap.option(ChannelOption.SO_LINGER, soLinger);
    }
    if (trafficClass != -1) {
        bootstrap.option(ChannelOption.IP_TOS, trafficClass);
    }
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout);
    bootstrap.option(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, tcpKeepAlive);
}

From source file:io.lettuce.core.AbstractRedisClient.java

License:Apache License

/**
 * Populate connection builder with necessary resources.
 *
 * @param socketAddressSupplier address supplier for initial connect and re-connect
 * @param connectionBuilder connection builder to configure the connection
 * @param redisURI URI of the Redis instance
 *///from  w w w  .j ava 2  s .c om
protected void connectionBuilder(Mono<SocketAddress> socketAddressSupplier, ConnectionBuilder connectionBuilder,
        RedisURI redisURI) {

    Bootstrap redisBootstrap = new Bootstrap();
    redisBootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
    redisBootstrap.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);
    redisBootstrap.option(ChannelOption.ALLOCATOR, BUF_ALLOCATOR);

    SocketOptions socketOptions = getOptions().getSocketOptions();

    redisBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,
            Math.toIntExact(socketOptions.getConnectTimeout().toMillis()));

    if (LettuceStrings.isEmpty(redisURI.getSocket())) {
        redisBootstrap.option(ChannelOption.SO_KEEPALIVE, socketOptions.isKeepAlive());
        redisBootstrap.option(ChannelOption.TCP_NODELAY, socketOptions.isTcpNoDelay());
    }

    connectionBuilder.timeout(redisURI.getTimeout());
    connectionBuilder.password(redisURI.getPassword());

    connectionBuilder.bootstrap(redisBootstrap);
    connectionBuilder.channelGroup(channels).connectionEvents(connectionEvents).timer(timer);
    connectionBuilder.socketAddressSupplier(socketAddressSupplier);
}

From source file:io.maelstorm.server.ServerInit.java

License:Open Source License

public void start(String configFile, RequestHandler handler) throws Exception {
    LOG.info("Starting.");
    AppendableCharSequenceAddon.configure();
    try {/*from  w ww  .  j a v  a  2 s.  com*/
        System.in.close(); // Release a FD we don't need.
    } catch (Exception e) {
        LOG.warn("Failed to close stdin", e);
    }
    Properties prop = getProperties(configFile);
    requestDistributor = handler;
    requestDistributor.setInitializer(this);
    String os = System.getProperty("os.name").toLowerCase(Locale.UK).trim();
    if (os.startsWith("linux")) {
        bossGroup = (null == bossGroup) ? new EpollEventLoopGroup(1) : bossGroup;
        workerGroup = (null == workerGroup) ? new EpollEventLoopGroup(NUM_WORKER_THREADS) : workerGroup;
    } else {
        bossGroup = (null == bossGroup) ? new NioEventLoopGroup(1) : bossGroup;
        workerGroup = (null == workerGroup) ? new NioEventLoopGroup(NUM_WORKER_THREADS) : workerGroup;
    }

    String[] servers = prop.getProperty("servers").split(",");
    for (String server : servers) {

        try {
            controller = new ServerBootstrap();
            controller.group(bossGroup, workerGroup);
            if (os.startsWith("linux")) {
                controller.channel(EpollServerSocketChannel.class);
                controller.option(EpollChannelOption.TCP_CORK, true);
            } else {
                controller.channel(NioServerSocketChannel.class);
            }
            controller.childHandler(new PipelineFactory(handler, getPipelineConfig(prop, server)));
            controller.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
            controller.option(ChannelOption.RCVBUF_ALLOCATOR, AdaptiveRecvByteBufAllocator.DEFAULT);
            controller.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,
                    getInt(prop, server, "connectTimeoutMillis"));
            controller.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 64 * 1024);
            controller.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 1 * 1024);
            controller.option(ChannelOption.SO_KEEPALIVE, getBoolean(prop, server, "SOKeepalive"));
            controller.option(ChannelOption.SO_REUSEADDR, true);
            controller.option(ChannelOption.TCP_NODELAY, true);
            controller.option(ChannelOption.SO_LINGER, 0);
            controller.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
            controller.childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 64 * 1024);
            controller.childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 10);
            controller.childOption(ChannelOption.SO_KEEPALIVE, true);
            controller.childOption(ChannelOption.SO_REUSEADDR, true);
            controller.childOption(ChannelOption.TCP_NODELAY, true);
            controller.childOption(ChannelOption.SO_LINGER, 0);
            controller.childOption(ChannelOption.SO_RCVBUF, 6291456);

            final InetSocketAddress addr = new InetSocketAddress(getInt(prop, server, "port"));
            ChannelFuture future = controller.bind(addr).sync();
            if (future.isSuccess())
                LOG.info("Server Ready to serve on " + addr);
            else
                throw new Exception("Address already in use");
        } catch (Throwable t) {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
            throw new RuntimeException("Initialization failed", t);
        }
    }
}

From source file:io.netty.example.ocsp.OcspClientExample.java

License:Apache License

public static void main(String[] args) throws Exception {
    if (!OpenSsl.isAvailable()) {
        throw new IllegalStateException("OpenSSL is not available!");
    }//from  w w w.ja v a  2s  . c  o m

    if (!OpenSsl.isOcspSupported()) {
        throw new IllegalStateException("OCSP is not supported!");
    }

    // Using Wikipedia as an example. I'd rather use Netty's own website
    // but the server (Cloudflare) doesn't support OCSP stapling. A few
    // other examples could be Microsoft or Squarespace. Use OpenSSL's
    // CLI client to assess if a server supports OCSP stapling. E.g.:
    //
    // openssl s_client -tlsextdebug -status -connect www.squarespace.com:443
    //
    String host = "www.wikipedia.org";

    ReferenceCountedOpenSslContext context = (ReferenceCountedOpenSslContext) SslContextBuilder.forClient()
            .sslProvider(SslProvider.OPENSSL).enableOcsp(true).build();

    try {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Promise<FullHttpResponse> promise = group.next().newPromise();

            Bootstrap bootstrap = new Bootstrap().channel(NioSocketChannel.class).group(group)
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5 * 1000)
                    .handler(newClientHandler(context, host, promise));

            Channel channel = bootstrap.connect(host, 443).syncUninterruptibly().channel();

            try {
                FullHttpResponse response = promise.get();
                ReferenceCountUtil.release(response);
            } finally {
                channel.close();
            }
        } finally {
            group.shutdownGracefully();
        }
    } finally {
        context.release();
    }
}

From source file:io.reactivesocket.netty.tcp.client.ClientTcpDuplexConnection.java

License:Apache License

public static Publisher<ClientTcpDuplexConnection> create(SocketAddress address,
        EventLoopGroup eventLoopGroup) {
    return s -> {
        CopyOnWriteArrayList<Observer<Frame>> subjects = new CopyOnWriteArrayList<>();
        ReactiveSocketClientHandler clientHandler = new ReactiveSocketClientHandler(subjects);
        Bootstrap bootstrap = new Bootstrap();
        ChannelFuture connect = bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_REUSEADDR, true)
                .option(ChannelOption.AUTO_READ, true).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override/*from  ww w. java2 s.com*/
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE >> 1, 0,
                                BitUtil.SIZE_OF_INT, -1 * BitUtil.SIZE_OF_INT, 0), clientHandler);
                    }
                }).connect(address);

        connect.addListener(connectFuture -> {
            if (connectFuture.isSuccess()) {
                Channel ch = connect.channel();
                s.onNext(new ClientTcpDuplexConnection(ch, subjects));
                s.onComplete();
            } else {
                s.onError(connectFuture.cause());
            }
        });
    };
}

From source file:io.reactivex.netty.protocol.http.client.HttpClientTest.java

License:Apache License

@Test
public void testConnectException() throws Exception {
    HttpClientBuilder<ByteBuf, ByteBuf> clientBuilder = new HttpClientBuilder<ByteBuf, ByteBuf>("localhost",
            8182);/* www.  ja  v  a  2 s .com*/
    HttpClient<ByteBuf, ByteBuf> client = clientBuilder.channelOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 100)
            .build();
    Observable<HttpClientResponse<ByteBuf>> response = client.submit(HttpClientRequest.createGet("/"));
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Throwable> ex = new AtomicReference<Throwable>();
    response.subscribe(new Observer<HttpClientResponse<ByteBuf>>() {
        @Override
        public void onCompleted() {
            latch.countDown();
        }

        @Override
        public void onError(Throwable e) {
            ex.set(e);
            latch.countDown();
        }

        @Override
        public void onNext(HttpClientResponse<ByteBuf> args) {
        }
    });
    latch.await();
    assertNotNull(ex.get());
    assertTrue(ex.get() instanceof ConnectException);
}

From source file:io.reactivex.netty.protocol.http.client.HttpClientTest.java

License:Apache License

@Test
public void testConnectException2() throws Exception {
    HttpClientBuilder<ByteBuf, ByteBuf> clientBuilder = new HttpClientBuilder<ByteBuf, ByteBuf>(
            "www.google.com", 81);
    HttpClient<ByteBuf, ByteBuf> client = clientBuilder.channelOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10)
            .build();//from w  w w . jav a2  s .  c  om
    Observable<HttpClientResponse<ByteBuf>> response = client.submit(HttpClientRequest.createGet("/"));
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Throwable> ex = new AtomicReference<Throwable>();
    response.subscribe(new Observer<HttpClientResponse<ByteBuf>>() {
        @Override
        public void onCompleted() {
            latch.countDown();
        }

        @Override
        public void onError(Throwable e) {
            ex.set(e);
            latch.countDown();
        }

        @Override
        public void onNext(HttpClientResponse<ByteBuf> args) {
        }
    });
    latch.await(10, TimeUnit.SECONDS);
    assertTrue(ex.get() instanceof ConnectTimeoutException);
}