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:org.apache.tajo.worker.RemoteFetcher.java
License:Apache License
public RemoteFetcher(TajoConf conf, URI uri, FileChunk chunk) { super(conf, uri, chunk); String scheme = uri.getScheme() == null ? "http" : uri.getScheme(); this.host = uri.getHost() == null ? "localhost" : uri.getHost(); this.port = uri.getPort(); if (port == -1) { if (scheme.equalsIgnoreCase("http")) { this.port = 80; } else if (scheme.equalsIgnoreCase("https")) { this.port = 443; }//from w w w . j av a 2 s .c om } bootstrap = new Bootstrap() .group(NettyUtils.getSharedEventLoopGroup(NettyUtils.GROUP.FETCHER, conf.getIntVar(TajoConf.ConfVars.SHUFFLE_RPC_CLIENT_WORKER_THREAD_NUM))) .channel(NioSocketChannel.class).option(ChannelOption.ALLOCATOR, NettyUtils.ALLOCATOR) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, conf.getIntVar(TajoConf.ConfVars.SHUFFLE_FETCHER_CONNECT_TIMEOUT) * 1000) .option(ChannelOption.SO_RCVBUF, 1048576) // set 1M .option(ChannelOption.TCP_NODELAY, true); }
From source file:org.asynchttpclient.netty.channel.ChannelManager.java
License:Open Source License
private Bootstrap newBootstrap(ChannelFactory<? extends Channel> channelFactory, EventLoopGroup eventLoopGroup, AsyncHttpClientConfig config) {/*from w ww . j a va 2s. co m*/ @SuppressWarnings("deprecation") Bootstrap bootstrap = new Bootstrap().channelFactory(channelFactory).group(eventLoopGroup)// // default to PooledByteBufAllocator .option(ChannelOption.ALLOCATOR, config.isUsePooledMemory() ? PooledByteBufAllocator.DEFAULT : UnpooledByteBufAllocator.DEFAULT)// .option(ChannelOption.TCP_NODELAY, config.isTcpNoDelay())// .option(ChannelOption.SO_REUSEADDR, config.isSoReuseAddress())// .option(ChannelOption.AUTO_CLOSE, false); if (config.getConnectTimeout() > 0) { bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.getConnectTimeout()); } if (config.getSoLinger() >= 0) { bootstrap.option(ChannelOption.SO_LINGER, config.getSoLinger()); } if (config.getSoSndBuf() >= 0) { bootstrap.option(ChannelOption.SO_SNDBUF, config.getSoSndBuf()); } if (config.getSoRcvBuf() >= 0) { bootstrap.option(ChannelOption.SO_RCVBUF, config.getSoRcvBuf()); } for (Entry<ChannelOption<Object>, Object> entry : config.getChannelOptions().entrySet()) { bootstrap.option(entry.getKey(), entry.getValue()); } return bootstrap; }
From source file:org.asynchttpclient.providers.netty.channel.ChannelManager.java
License:Open Source License
public ChannelManager(AsyncHttpClientConfig config, NettyAsyncHttpProviderConfig nettyConfig, Timer nettyTimer) {//from w ww . ja va 2 s .c o m this.config = config; this.nettyConfig = nettyConfig; ChannelPool channelPool = nettyConfig.getChannelPool(); if (channelPool == null && config.isAllowPoolingConnections()) { channelPool = new DefaultChannelPool(config, nettyTimer); } else if (channelPool == null) { channelPool = new NoopChannelPool(); } this.channelPool = channelPool; maxConnectionsEnabled = config.getMaxConnections() > 0; maxConnectionsPerHostEnabled = config.getMaxConnectionsPerHost() > 0; if (maxConnectionsEnabled) { openChannels = new CleanupChannelGroup("asyncHttpClient") { @Override public boolean remove(Object o) { boolean removed = super.remove(o); if (removed) { freeChannels.release(); if (maxConnectionsPerHostEnabled) { String poolKey = channel2KeyPool.remove(Channel.class.cast(o)); if (poolKey != null) { Semaphore freeChannelsForHost = freeChannelsPerHost.get(poolKey); if (freeChannelsForHost != null) freeChannelsForHost.release(); } } } return removed; } }; freeChannels = new Semaphore(config.getMaxConnections()); } else { openChannels = new CleanupChannelGroup("asyncHttpClient"); freeChannels = null; } if (maxConnectionsPerHostEnabled) { freeChannelsPerHost = new ConcurrentHashMap<String, Semaphore>(); channel2KeyPool = new ConcurrentHashMap<Channel, String>(); } else { freeChannelsPerHost = null; channel2KeyPool = null; } handshakeTimeout = nettyConfig.getHandshakeTimeout(); // check if external EventLoopGroup is defined allowReleaseEventLoopGroup = nettyConfig.getEventLoopGroup() == null; eventLoopGroup = allowReleaseEventLoopGroup ? new NioEventLoopGroup() : nettyConfig.getEventLoopGroup(); if (!(eventLoopGroup instanceof NioEventLoopGroup)) throw new IllegalArgumentException("Only Nio is supported"); plainBootstrap = new Bootstrap().channel(NioSocketChannel.class).group(eventLoopGroup); secureBootstrap = new Bootstrap().channel(NioSocketChannel.class).group(eventLoopGroup); webSocketBootstrap = new Bootstrap().channel(NioSocketChannel.class).group(eventLoopGroup); secureWebSocketBootstrap = new Bootstrap().channel(NioSocketChannel.class).group(eventLoopGroup); if (config.getConnectTimeout() > 0) nettyConfig.addChannelOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.getConnectTimeout()); for (Entry<ChannelOption<Object>, Object> entry : nettyConfig.propertiesSet()) { ChannelOption<Object> key = entry.getKey(); Object value = entry.getValue(); plainBootstrap.option(key, value); webSocketBootstrap.option(key, value); secureBootstrap.option(key, value); secureWebSocketBootstrap.option(key, value); } }
From source file:org.asynchttpclient.providers.netty.channel.Channels.java
License:Apache License
public Channels(final AsyncHttpClientConfig config, NettyAsyncHttpProviderConfig nettyProviderConfig) { this.config = config; this.nettyProviderConfig = nettyProviderConfig; // FIXME https://github.com/netty/netty/issues/2132 if (config.getRequestCompressionLevel() > 0) { LOGGER.warn(//from w ww. j ava 2 s . c om "Request was enabled but Netty actually doesn't support this feature, see https://github.com/netty/netty/issues/2132"); } // check if external EventLoopGroup is defined allowReleaseEventLoopGroup = nettyProviderConfig.getEventLoopGroup() == null; eventLoopGroup = allowReleaseEventLoopGroup ? new NioEventLoopGroup() : nettyProviderConfig.getEventLoopGroup(); // check if external HashedWheelTimer is defined allowStopNettyTimer = nettyProviderConfig.getNettyTimer() == null; nettyTimer = allowStopNettyTimer ? newNettyTimer() : nettyProviderConfig.getNettyTimer(); handshakeTimeoutInMillis = nettyProviderConfig.getHandshakeTimeoutInMillis(); if (!(eventLoopGroup instanceof NioEventLoopGroup)) throw new IllegalArgumentException("Only Nio is supported"); plainBootstrap = new Bootstrap().channel(NioSocketChannel.class).group(eventLoopGroup); secureBootstrap = new Bootstrap().channel(NioSocketChannel.class).group(eventLoopGroup); webSocketBootstrap = new Bootstrap().channel(NioSocketChannel.class).group(eventLoopGroup); secureWebSocketBootstrap = new Bootstrap().channel(NioSocketChannel.class).group(eventLoopGroup); ChannelPool cp = nettyProviderConfig.getChannelPool(); if (cp == null) { if (config.getAllowPoolingConnection()) { cp = new DefaultChannelPool(config, nettyTimer); } else { cp = new NonChannelPool(); } } this.channelPool = cp; if (config.getMaxTotalConnections() != -1) { trackConnections = true; freeConnections = new Semaphore(config.getMaxTotalConnections()); } else { trackConnections = false; freeConnections = null; } Map<String, ChannelOption<Object>> optionMap = new HashMap<String, ChannelOption<Object>>(); for (Field field : ChannelOption.class.getDeclaredFields()) { if (field.getType().isAssignableFrom(ChannelOption.class)) { field.setAccessible(true); try { optionMap.put(field.getName(), (ChannelOption<Object>) field.get(null)); } catch (IllegalAccessException ex) { throw new Error(ex); } } } if (nettyProviderConfig != null) { for (Entry<String, Object> entry : nettyProviderConfig.propertiesSet()) { ChannelOption<Object> key = optionMap.get(entry.getKey()); if (key != null) { Object value = entry.getValue(); plainBootstrap.option(key, value); webSocketBootstrap.option(key, value); secureBootstrap.option(key, value); secureWebSocketBootstrap.option(key, value); } else { throw new IllegalArgumentException("Unknown config property " + entry.getKey()); } } } int timeOut = config.getConnectionTimeoutInMs() > 0 ? config.getConnectionTimeoutInMs() : Integer.MAX_VALUE; plainBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, timeOut); webSocketBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, timeOut); secureBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, timeOut); secureWebSocketBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, timeOut); }
From source file:org.asynchttpclient.providers.netty4.channel.ChannelManager.java
License:Open Source License
public ChannelManager(AsyncHttpClientConfig config, NettyAsyncHttpProviderConfig nettyConfig, Timer nettyTimer) {/*from ww w . j av a 2 s.co m*/ this.config = config; this.nettyConfig = nettyConfig; this.sslEngineFactory = nettyConfig.getSslEngineFactory() != null ? nettyConfig.getSslEngineFactory() : new SSLEngineFactory.DefaultSSLEngineFactory(config); ChannelPool channelPool = nettyConfig.getChannelPool(); if (channelPool == null && config.isAllowPoolingConnections()) { channelPool = new DefaultChannelPool(config, nettyTimer); } else if (channelPool == null) { channelPool = new NoopChannelPool(); } this.channelPool = channelPool; maxConnectionsEnabled = config.getMaxConnections() > 0; maxConnectionsPerHostEnabled = config.getMaxConnectionsPerHost() > 0; if (maxConnectionsEnabled) { openChannels = new CleanupChannelGroup("asyncHttpClient") { @Override public boolean remove(Object o) { boolean removed = super.remove(o); if (removed) { freeChannels.release(); if (maxConnectionsPerHostEnabled) { String poolKey = channel2KeyPool.remove(Channel.class.cast(o)); if (poolKey != null) { Semaphore freeChannelsForHost = freeChannelsPerHost.get(poolKey); if (freeChannelsForHost != null) freeChannelsForHost.release(); } } } return removed; } }; freeChannels = new Semaphore(config.getMaxConnections()); } else { openChannels = new CleanupChannelGroup("asyncHttpClient"); freeChannels = null; } if (maxConnectionsPerHostEnabled) { freeChannelsPerHost = new ConcurrentHashMap<String, Semaphore>(); channel2KeyPool = new ConcurrentHashMap<Channel, String>(); } else { freeChannelsPerHost = null; channel2KeyPool = null; } handshakeTimeout = nettyConfig.getHandshakeTimeout(); // check if external EventLoopGroup is defined allowReleaseEventLoopGroup = nettyConfig.getEventLoopGroup() == null; eventLoopGroup = allowReleaseEventLoopGroup ? new NioEventLoopGroup() : nettyConfig.getEventLoopGroup(); if (!(eventLoopGroup instanceof NioEventLoopGroup)) throw new IllegalArgumentException("Only Nio is supported"); plainBootstrap = new Bootstrap().channel(NioSocketChannel.class).group(eventLoopGroup); secureBootstrap = new Bootstrap().channel(NioSocketChannel.class).group(eventLoopGroup); webSocketBootstrap = new Bootstrap().channel(NioSocketChannel.class).group(eventLoopGroup); secureWebSocketBootstrap = new Bootstrap().channel(NioSocketChannel.class).group(eventLoopGroup); if (config.getConnectTimeout() > 0) nettyConfig.addChannelOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.getConnectTimeout()); for (Entry<ChannelOption<Object>, Object> entry : nettyConfig.propertiesSet()) { ChannelOption<Object> key = entry.getKey(); Object value = entry.getValue(); plainBootstrap.option(key, value); webSocketBootstrap.option(key, value); secureBootstrap.option(key, value); secureWebSocketBootstrap.option(key, value); } }
From source file:org.betawares.jorre.Client.java
License:Open Source License
/** * Connect to a {@link Server} using the specified {@link Connection} settings. This call * will block until successful or an exception is thrown. * /*from w w w . j av a 2 s . c om*/ * @param connection a {@link Connection} instance specifying the connection settings * @return true if the connection was successful, false otherwise */ public boolean connect(Connection connection) { clientMessageHandler = new ClientMessageHandler(this, connection.getMaxResponseAge()); group = new NioEventLoopGroup(); try { if (connection.isSSL()) { sslCtx = SslContextBuilder.forClient().build(); } else { sslCtx = null; } Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { if (sslCtx != null) { ch.pipeline() .addLast(sslCtx.newHandler(ch.alloc(), connection.getHost(), connection.getPort())); } ch.pipeline().addLast(new ObjectDecoder(10 * 1024 * 1024, ClassResolvers.cacheDisabled(null))); ch.pipeline().addLast(new ObjectEncoder()); // ch.pipeline().addLast("messageInspector", new ClientMessageInspector()); ch.pipeline().addLast("idleStateHandler", new IdleStateHandler(connection.getIdleTimeout(), connection.getIdlePingTime(), 0, TimeUnit.MILLISECONDS)); ch.pipeline().addLast("heartbeatHandler", new ClientHeartbeatHandler(Client.this)); ch.pipeline().addLast("pingMessageHandler", new PingMessageHandler()); ch.pipeline().addLast("pongMessageHandler", new PongMessageHandler()); ch.pipeline().addLast("clientMessageHandler", clientMessageHandler); ch.pipeline().addLast("exceptionHandler", new ChannelHandlerAdapter() { @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { logger.error("Communications error", cause); Client.this.disconnect(DisconnectReason.IOError, true); } }); } }); bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connection.getConnectionTimeout()); ChannelFuture future = bootstrap.connect(connection.getHost(), connection.getPort()); channel = future.sync().channel(); return true; } catch (SSLException | InterruptedException ex) { logger.fatal("Error connecting", ex); disconnect(DisconnectReason.IOError, true); } return false; }
From source file:org.eclipse.californium.elements.tcp.TcpClientConnector.java
License:Open Source License
@Override public synchronized void start() throws IOException { if (rawDataChannel == null) { throw new IllegalStateException("Cannot start without message handler."); }//w w w . j av a 2 s.com if (workerGroup != null) { throw new IllegalStateException("Connector already started"); } workerGroup = new NioEventLoopGroup(numberOfThreads); poolMap = new AbstractChannelPoolMap<SocketAddress, ChannelPool>() { @Override protected ChannelPool newPool(SocketAddress key) { Bootstrap bootstrap = new Bootstrap().group(workerGroup).channel(NioSocketChannel.class) .option(ChannelOption.SO_KEEPALIVE, true).option(ChannelOption.AUTO_READ, true) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeoutMillis).remoteAddress(key); // We multiplex over the same TCP connection, so don't acquire // more than one connection per endpoint. // TODO: But perhaps we could make it a configurable property. if (USE_FIXED_CONNECTION_POOL) { return new FixedChannelPool(bootstrap, new MyChannelPoolHandler(key), 1); } else { return new SimpleChannelPool(bootstrap, new MyChannelPoolHandler(key)); } } }; }
From source file:org.eclipse.milo.opcua.stack.client.UaTcpStackClient.java
License:Open Source 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 w ww . j a v a 2 s.c o m*/ protected void initChannel(SocketChannel channel) throws Exception { UaTcpClientAcknowledgeHandler acknowledgeHandler = new UaTcpClientAcknowledgeHandler(client, existingChannel, handshake); channel.pipeline().addLast(acknowledgeHandler); } }); try { URI uri = new URI(client.getEndpointUrl()).parseServerAuthority(); bootstrap.connect(uri.getHost(), uri.getPort()).addListener((ChannelFuture f) -> { if (!f.isSuccess()) { handshake.completeExceptionally(f.cause()); } }); } catch (Throwable e) { UaException failure = new UaException(StatusCodes.Bad_TcpEndpointUrlInvalid, e); handshake.completeExceptionally(failure); } return handshake; }
From source file:org.elasticsearch.hadoop.transport.netty4.Netty4Transport.java
License:Apache License
private Bootstrap createBootstrap() { final Bootstrap bootstrap = new Bootstrap(); if (TCP_BLOCKING_CLIENT.get(settings)) { bootstrap.group(new OioEventLoopGroup(1, daemonThreadFactory(settings, TRANSPORT_CLIENT_WORKER_THREAD_NAME_PREFIX))); bootstrap.channel(OioSocketChannel.class); } else {//from www .j a v a 2s . c o m bootstrap.group(new NioEventLoopGroup(workerCount, daemonThreadFactory(settings, TRANSPORT_CLIENT_BOSS_THREAD_NAME_PREFIX))); bootstrap.channel(NioSocketChannel.class); } bootstrap.handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast("size", new Netty4SizeHeaderFrameDecoder()); // using a dot as a prefix means this cannot come from any settings parsed ch.pipeline().addLast("dispatcher", new Netty4MessageChannelHandler(Netty4Transport.this, ".client")); } }); bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, Math.toIntExact(connectTimeout.millis())); bootstrap.option(ChannelOption.TCP_NODELAY, TCP_NO_DELAY.get(settings)); bootstrap.option(ChannelOption.SO_KEEPALIVE, TCP_KEEP_ALIVE.get(settings)); final ByteSizeValue tcpSendBufferSize = TCP_SEND_BUFFER_SIZE.get(settings); if (tcpSendBufferSize.bytes() > 0) { bootstrap.option(ChannelOption.SO_SNDBUF, Math.toIntExact(tcpSendBufferSize.bytes())); } final ByteSizeValue tcpReceiveBufferSize = TCP_RECEIVE_BUFFER_SIZE.get(settings); if (tcpReceiveBufferSize.bytes() > 0) { bootstrap.option(ChannelOption.SO_RCVBUF, Math.toIntExact(tcpReceiveBufferSize.bytes())); } bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, recvByteBufAllocator); final boolean reuseAddress = TCP_REUSE_ADDRESS.get(settings); bootstrap.option(ChannelOption.SO_REUSEADDR, reuseAddress); bootstrap.validate(); return bootstrap; }
From source file:org.elasticsearch.transport.netty4.Netty4Transport.java
License:Apache License
private Bootstrap createBootstrap() { final Bootstrap bootstrap = new Bootstrap(); if (TCP_BLOCKING_CLIENT.get(settings)) { bootstrap.group(new OioEventLoopGroup(1, daemonThreadFactory(settings, TRANSPORT_CLIENT_WORKER_THREAD_NAME_PREFIX))); bootstrap.channel(OioSocketChannel.class); } else {//from ww w . j av a2s . c o m bootstrap.group(new NioEventLoopGroup(workerCount, daemonThreadFactory(settings, TRANSPORT_CLIENT_BOSS_THREAD_NAME_PREFIX))); bootstrap.channel(NioSocketChannel.class); } bootstrap.handler(getClientChannelInitializer()); bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, Math.toIntExact(connectTimeout.millis())); bootstrap.option(ChannelOption.TCP_NODELAY, TCP_NO_DELAY.get(settings)); bootstrap.option(ChannelOption.SO_KEEPALIVE, TCP_KEEP_ALIVE.get(settings)); final ByteSizeValue tcpSendBufferSize = TCP_SEND_BUFFER_SIZE.get(settings); if (tcpSendBufferSize.bytes() > 0) { bootstrap.option(ChannelOption.SO_SNDBUF, Math.toIntExact(tcpSendBufferSize.bytes())); } final ByteSizeValue tcpReceiveBufferSize = TCP_RECEIVE_BUFFER_SIZE.get(settings); if (tcpReceiveBufferSize.bytes() > 0) { bootstrap.option(ChannelOption.SO_RCVBUF, Math.toIntExact(tcpReceiveBufferSize.bytes())); } bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, recvByteBufAllocator); final boolean reuseAddress = TCP_REUSE_ADDRESS.get(settings); bootstrap.option(ChannelOption.SO_REUSEADDR, reuseAddress); bootstrap.validate(); return bootstrap; }