List of usage examples for io.netty.channel ChannelOption CONNECT_TIMEOUT_MILLIS
ChannelOption CONNECT_TIMEOUT_MILLIS
To view the source code for io.netty.channel ChannelOption CONNECT_TIMEOUT_MILLIS.
Click Source Link
From source file:com.king.platform.net.http.netty.ChannelManager.java
License:Apache License
public ChannelManager(NioEventLoopGroup nioEventLoop, final HttpClientHandler httpClientHandler, Timer nettyTimer, TimeProvider timeProvider, ChannelPool channelPool, final ConfMap confMap, RootEventBus rootEventBus) {//from w ww . j ava 2 s . c o m this.eventLoopGroup = nioEventLoop; this.nettyTimer = nettyTimer; this.timeProvider = timeProvider; this.channelPool = channelPool; this.confMap = confMap; plainBootstrap = new Bootstrap().channel(NioSocketChannel.class).group(eventLoopGroup); plainBootstrap.handler(new ChannelInitializer() { @Override protected void initChannel(Channel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); addLoggingIfDesired(pipeline, confMap.get(ConfKeys.NETTY_TRACE_LOGS)); pipeline.addLast("http-codec", newHttpClientCodec()); pipeline.addLast("inflater", new HttpContentDecompressor()); pipeline.addLast("chunkedWriter", new ChunkedWriteHandler()); pipeline.addLast("httpClientHandler", httpClientHandler); } }); secureBootstrap = new Bootstrap().channel(NioSocketChannel.class).group(eventLoopGroup); secureBootstrap.handler(new ChannelInitializer() { @Override protected void initChannel(Channel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); SslInitializer sslInitializer = new SslInitializer( new SSLFactory(confMap.get(ConfKeys.SSL_ALLOW_ALL_CERTIFICATES)), confMap.get(ConfKeys.SSL_HANDSHAKE_TIMEOUT_MILLIS)); pipeline.addLast(SslInitializer.NAME, sslInitializer); addLoggingIfDesired(pipeline, confMap.get(ConfKeys.NETTY_TRACE_LOGS)); pipeline.addLast("http-codec", newHttpClientCodec()); pipeline.addLast("inflater", new HttpContentDecompressor()); pipeline.addLast("chunkedWriter", new ChunkedWriteHandler()); pipeline.addLast("httpClientHandler", httpClientHandler); } }); secureBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, confMap.get(ConfKeys.CONNECT_TIMEOUT_MILLIS)); plainBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, confMap.get(ConfKeys.CONNECT_TIMEOUT_MILLIS)); NettyChannelOptions nettyChannelOptions = confMap.get(ConfKeys.NETTY_CHANNEL_OPTIONS); for (ChannelOption channelOption : nettyChannelOptions.keys()) { plainBootstrap.option(channelOption, nettyChannelOptions.get(channelOption)); secureBootstrap.option(channelOption, nettyChannelOptions.get(channelOption)); } rootEventBus.subscribePermanently(Event.ERROR, new ErrorCallback()); rootEventBus.subscribePermanently(Event.COMPLETED, new CompletedCallback()); rootEventBus.subscribePermanently(Event.EXECUTE_REQUEST, new ExecuteRequestCallback()); }
From source file:com.lambdaworks.redis.AbstractRedisClient.java
License:Apache License
/** * Populate connection builder with necessary resources. * * @param handler instance of a CommandHandler for writing redis commands * @param connection implementation of a RedisConnection * @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 a v a 2s . c om*/ protected void connectionBuilder(CommandHandler<?, ?> handler, RedisChannelHandler<?, ?> connection, Supplier<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, (int) socketOptions.getConnectTimeoutUnit().toMillis(socketOptions.getConnectTimeout())); if (LettuceStrings.isEmpty(redisURI.getSocket())) { redisBootstrap.option(ChannelOption.SO_KEEPALIVE, socketOptions.isKeepAlive()); redisBootstrap.option(ChannelOption.TCP_NODELAY, socketOptions.isTcpNoDelay()); } connectionBuilder.timeout(redisURI.getTimeout(), redisURI.getUnit()); connectionBuilder.password(redisURI.getPassword()); connectionBuilder.bootstrap(redisBootstrap); connectionBuilder.channelGroup(channels).connectionEvents(connectionEvents).timer(timer); connectionBuilder.commandHandler(handler).socketAddressSupplier(socketAddressSupplier) .connection(connection); connectionBuilder.workerPool(genericWorkerPool); }
From source file:com.linecorp.armeria.client.ClientFactoryBuilder.java
License:Apache License
/** * Sets the timeout of a socket connection attempt in milliseconds. *//*from w w w . ja v a 2s .c o m*/ public ClientFactoryBuilder connectTimeoutMillis(long connectTimeoutMillis) { checkArgument(connectTimeoutMillis > 0, "connectTimeoutMillis: %s (expected: > 0)", connectTimeoutMillis); return socketOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, ConvertUtils.safeLongToInt(connectTimeoutMillis)); }
From source file:com.linecorp.armeria.client.HttpSessionChannelFactory.java
License:Apache License
HttpSessionChannelFactory(HttpClientFactory clientFactory, EventLoop eventLoop) { this.clientFactory = clientFactory; this.eventLoop = eventLoop; baseBootstrap = clientFactory.newBootstrap(); baseBootstrap.group(eventLoop);// w w w. j av a 2 s . c o m connectTimeoutMillis = (Integer) baseBootstrap.config().options().get(ChannelOption.CONNECT_TIMEOUT_MILLIS); bootstrapMap = Collections.synchronizedMap(new EnumMap<>(SessionProtocol.class)); }
From source file:com.linecorp.armeria.client.NonDecoratingClientFactory.java
License:Apache License
private NonDecoratingClientFactory(SessionOptions options, Function<TransportType, ThreadFactory> threadFactoryFactory) { requireNonNull(options, "options"); requireNonNull(threadFactoryFactory, "threadFactoryFactory"); final Bootstrap baseBootstrap = new Bootstrap(); baseBootstrap.channel(channelType()); baseBootstrap.resolver(options.addressResolverGroup().orElseGet(DnsAddressResolverGroup5657::new)); baseBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, ConvertUtils.safeLongToInt(options.connectTimeoutMillis())); baseBootstrap.option(ChannelOption.SO_KEEPALIVE, true); final Optional<EventLoopGroup> eventLoopOption = options.eventLoopGroup(); if (eventLoopOption.isPresent()) { eventLoopGroup = eventLoopOption.get(); closeEventLoopGroup = false;/*w ww .j a v a 2s . c om*/ } else { eventLoopGroup = createGroup(threadFactoryFactory); closeEventLoopGroup = true; } this.baseBootstrap = baseBootstrap; this.options = options; }
From source file:com.linecorp.armeria.client.RemoteInvokerFactory.java
License:Apache License
private RemoteInvokerFactory(RemoteInvokerOptions options, Function<TransportType, ThreadFactory> threadFactoryFactory) { requireNonNull(options, "options"); requireNonNull(threadFactoryFactory, "threadFactoryFactory"); final Bootstrap baseBootstrap = new Bootstrap(); baseBootstrap.channel(channelType()); baseBootstrap.resolver(options.addressResolverGroup().orElseGet( () -> new DnsAddressResolverGroup(datagramChannelType(), DnsServerAddresses.defaultAddresses()))); baseBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, ConvertUtils.safeLongToInt(options.connectTimeoutMillis())); baseBootstrap.option(ChannelOption.SO_KEEPALIVE, true); final Optional<EventLoopGroup> eventLoopOption = options.eventLoopGroup(); if (eventLoopOption.isPresent()) { eventLoopGroup = eventLoopOption.get(); closeEventLoopGroup = false;/* ww w.j a v a2 s .c o m*/ } else { eventLoopGroup = createGroup(threadFactoryFactory); closeEventLoopGroup = true; } final EnumMap<SessionProtocol, RemoteInvoker> remoteInvokers = new EnumMap<>(SessionProtocol.class); final HttpRemoteInvoker remoteInvoker = new HttpRemoteInvoker(baseBootstrap, options); SessionProtocol.ofHttp().forEach(protocol -> remoteInvokers.put(protocol, remoteInvoker)); this.remoteInvokers = Collections.unmodifiableMap(remoteInvokers); }
From source file:com.look.netty.demo.socksproxy.SocksServerConnectHandler.java
License:Apache License
@Override public void channelRead0(final ChannelHandlerContext ctx, final SocksMessage message) throws Exception { if (message instanceof Socks4CommandRequest) { final Socks4CommandRequest request = (Socks4CommandRequest) message; Promise<Channel> promise = ctx.executor().newPromise(); promise.addListener(new FutureListener<Channel>() { @Override//from w w w.j a v a 2 s. c o m public void operationComplete(final Future<Channel> future) throws Exception { final Channel outboundChannel = future.getNow(); if (future.isSuccess()) { ChannelFuture responseFuture = ctx.channel() .writeAndFlush(new DefaultSocks4CommandResponse(Socks4CommandStatus.SUCCESS)); responseFuture.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 DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED)); 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.dstAddr(), request.dstPort()).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 DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED)); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); } else if (message instanceof Socks5CommandRequest) { final Socks5CommandRequest request = (Socks5CommandRequest) message; Promise<Channel> promise = ctx.executor().newPromise(); promise.addListener(new FutureListener<Channel>() { @Override public void operationComplete(final Future<Channel> future) throws Exception { final Channel outboundChannel = future.getNow(); if (future.isSuccess()) { ChannelFuture responseFuture = ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse( Socks5CommandStatus.SUCCESS, request.dstAddrType())); responseFuture.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 DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE, request.dstAddrType())); 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.dstAddr(), request.dstPort()).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 DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE, request.dstAddrType())); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); } else { ctx.close(); } }
From source file:com.mastfrog.netty.http.client.HttpClient.java
License:Open Source License
@SuppressWarnings("unchecked") private synchronized Bootstrap start(HostAndPort hostAndPort) { if (bootstrap == null) { bootstrap = new Bootstrap(); bootstrap.group(group);//w w w . j ava 2 s. co m bootstrap.handler(new Initializer(hostAndPort, handler, null, false, maxChunkSize, maxInitialLineLength, maxHeadersSize, compress)); bootstrap.option(ChannelOption.TCP_NODELAY, true); bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); bootstrap.option(ChannelOption.SO_REUSEADDR, false); if (timeout != null) { bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) timeout.getMillis()); } for (ChannelOptionSetting<?> setting : settings) { option(bootstrap, setting); } bootstrap.channelFactory(new NioChannelFactory()); } return bootstrap; }
From source file:com.mongodb.connection.netty.NettyStream.java
License:Apache License
@Override public void openAsync(final AsyncCompletionHandler<Void> handler) { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(workerGroup);//from w w w . ja v a 2 s . co m bootstrap.channel(NioSocketChannel.class); bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, settings.getConnectTimeout(MILLISECONDS)); bootstrap.option(ChannelOption.TCP_NODELAY, true); bootstrap.option(ChannelOption.SO_KEEPALIVE, settings.isKeepAlive()); if (settings.getReceiveBufferSize() > 0) { bootstrap.option(ChannelOption.SO_RCVBUF, settings.getReceiveBufferSize()); } if (settings.getSendBufferSize() > 0) { bootstrap.option(ChannelOption.SO_SNDBUF, settings.getSendBufferSize()); } bootstrap.option(ChannelOption.ALLOCATOR, allocator); bootstrap.handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(final SocketChannel ch) throws Exception { if (sslSettings.isEnabled()) { SSLEngine engine = SSLContext.getDefault().createSSLEngine(address.getHost(), address.getPort()); engine.setUseClientMode(true); if (!sslSettings.isInvalidHostNameAllowed()) { engine.setSSLParameters(enableHostNameVerification(engine.getSSLParameters())); } ch.pipeline().addFirst("ssl", new SslHandler(engine, false)); } ch.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(settings.getReadTimeout(MILLISECONDS), MILLISECONDS)); ch.pipeline().addLast(new InboundBufferHandler()); } }); final ChannelFuture channelFuture = bootstrap.connect(address.getHost(), address.getPort()); channelFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture future) throws Exception { if (future.isSuccess()) { channel = channelFuture.channel(); handler.completed(null); } else { handler.failed(future.cause()); } } }); }
From source file:com.mpush.netty.client.NettyClient.java
License:Apache License
@Override public void start(final Listener listener) { if (started.compareAndSet(false, true)) { Bootstrap bootstrap = new Bootstrap(); workerGroup = new NioEventLoopGroup(); bootstrap.group(workerGroup)// .option(ChannelOption.TCP_NODELAY, true)// .option(ChannelOption.SO_REUSEADDR, true)// .option(ChannelOption.SO_KEEPALIVE, true)// .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)// .channel(NioSocketChannel.class).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 4000); bootstrap.handler(new ChannelInitializer<SocketChannel>() { // (4) @Override// w ww . j a v a2 s . c o m public void initChannel(SocketChannel ch) throws Exception { initPipeline(ch.pipeline()); } }); ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port)); future.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { if (listener != null) listener.onSuccess(port); LOGGER.info("start netty client success, host={}, port={}", host, port); } else { if (listener != null) listener.onFailure(future.cause()); LOGGER.error("start netty client failure, host={}, port={}", host, port, future.cause()); } } }); } else { listener.onFailure(new ServiceException("client has started!")); } }