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.xx_dev.apn.proxy.ApnProxyUserAgentTunnelHandler.java
License:Apache License
@Override public void channelRead(final ChannelHandlerContext uaChannelCtx, Object msg) throws Exception { if (msg instanceof HttpRequest) { final HttpRequest httpRequest = (HttpRequest) msg; //Channel uaChannel = uaChannelCtx.channel(); // connect remote Bootstrap bootstrap = new Bootstrap(); bootstrap.group(uaChannelCtx.channel().eventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .option(ChannelOption.AUTO_READ, false) .handler(new ApnProxyTunnelChannelInitializer(uaChannelCtx.channel())); final ApnProxyRemote apnProxyRemote = uaChannelCtx.channel() .attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY).get().getRemote(); // set local address if (StringUtils.isNotBlank(ApnProxyLocalAddressChooser.choose(apnProxyRemote.getRemoteHost()))) { bootstrap.localAddress(new InetSocketAddress( (ApnProxyLocalAddressChooser.choose(apnProxyRemote.getRemoteHost())), 0)); }/*from w ww. j a va 2 s . c om*/ bootstrap.connect(apnProxyRemote.getRemoteHost(), apnProxyRemote.getRemotePort()) .addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture future1) throws Exception { if (future1.isSuccess()) { if (apnProxyRemote.isAppleyRemoteRule()) { uaChannelCtx.pipeline().remove("codec"); uaChannelCtx.pipeline().remove(ApnProxyPreHandler.HANDLER_NAME); uaChannelCtx.pipeline().remove(ApnProxyUserAgentTunnelHandler.HANDLER_NAME); // add relay handler uaChannelCtx.pipeline() .addLast(new ApnProxyRelayHandler("UA --> Remote", future1.channel())); future1.channel() .writeAndFlush(Unpooled.copiedBuffer( constructConnectRequestForProxy(httpRequest, apnProxyRemote), CharsetUtil.UTF_8)) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future2) throws Exception { if (!future2.channel().config() .getOption(ChannelOption.AUTO_READ)) { future2.channel().read(); } } }); } else { HttpResponse proxyConnectSuccessResponse = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, new HttpResponseStatus(200, "Connection established")); uaChannelCtx.writeAndFlush(proxyConnectSuccessResponse) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future2) throws Exception { // remove handlers uaChannelCtx.pipeline().remove("codec"); uaChannelCtx.pipeline().remove(ApnProxyPreHandler.HANDLER_NAME); uaChannelCtx.pipeline() .remove(ApnProxyUserAgentTunnelHandler.HANDLER_NAME); // add relay handler uaChannelCtx.pipeline() .addLast(new ApnProxyRelayHandler( "UA --> " + apnProxyRemote.getRemoteAddr(), future1.channel())); } }); } } else { if (uaChannelCtx.channel().isActive()) { uaChannelCtx.channel().writeAndFlush(Unpooled.EMPTY_BUFFER) .addListener(ChannelFutureListener.CLOSE); } } } }); } ReferenceCountUtil.release(msg); }
From source file:com.xx_dev.apn.socks.remote.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// www . j a va 2 s .c o m public void operationComplete(final Future<Channel> future) throws Exception { final Channel outboundChannel = future.getNow(); if (future.isSuccess()) { restLogger.info(request.host() + ":" + request.port() + "," + "T"); 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 { restLogger.info(request.host() + ":" + request.port() + "," + "F"); 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. restLogger.info(request.host() + ":" + request.port() + "," + "F"); ctx.channel() .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType())); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); }
From source file:com.xx_dev.apn.socks.test.SocksClient.java
License:Apache License
public static void main(String[] args) throws Throwable { EventLoopGroup group = new NioEventLoopGroup(); Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000) .option(ChannelOption.SO_KEEPALIVE, true).handler(new SocksClientInitializer()); // Make the connection attempt. b.connect("112.124.38.73", 8888).sync().channel().closeFuture().sync(); group.shutdownGracefully();/*from w ww .j a v a 2 s.c om*/ }
From source file:com.yahoo.pulsar.client.impl.ConnectionPool.java
License:Apache License
public ConnectionPool(final PulsarClientImpl client, EventLoopGroup eventLoopGroup) { this.eventLoopGroup = eventLoopGroup; this.maxConnectionsPerHosts = client.getConfiguration().getConnectionsPerBroker(); pool = new ConcurrentHashMap<>(); bootstrap = new Bootstrap(); bootstrap.group(eventLoopGroup);/*from w w w . j a va 2 s .c o m*/ if (SystemUtils.IS_OS_LINUX && eventLoopGroup instanceof EpollEventLoopGroup) { bootstrap.channel(EpollSocketChannel.class); } else { bootstrap.channel(NioSocketChannel.class); } bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000); bootstrap.option(ChannelOption.TCP_NODELAY, client.getConfiguration().isUseTcpNoDelay()); bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); bootstrap.handler(new ChannelInitializer<SocketChannel>() { public void initChannel(SocketChannel ch) throws Exception { ClientConfiguration clientConfig = client.getConfiguration(); if (clientConfig.isUseTls()) { SslContextBuilder builder = SslContextBuilder.forClient(); if (clientConfig.isTlsAllowInsecureConnection()) { builder.trustManager(InsecureTrustManagerFactory.INSTANCE); } else { if (clientConfig.getTlsTrustCertsFilePath().isEmpty()) { // Use system default builder.trustManager((File) null); } else { File trustCertCollection = new File(clientConfig.getTlsTrustCertsFilePath()); builder.trustManager(trustCertCollection); } } // Set client certificate if available AuthenticationDataProvider authData = clientConfig.getAuthentication().getAuthData(); if (authData.hasDataForTls()) { builder.keyManager(authData.getTlsPrivateKey(), (X509Certificate[]) authData.getTlsCertificates()); } SslContext sslCtx = builder.build(); ch.pipeline().addLast(TLS_HANDLER, sslCtx.newHandler(ch.alloc())); } ch.pipeline().addLast("frameDecoder", new PulsarLengthFieldFrameDecoder(MaxMessageSize, 0, 4, 0, 4)); ch.pipeline().addLast("handler", new ClientCnx(client)); } }); }
From source file:com.zaradai.distributor.messaging.netty.NettyClient.java
License:Apache License
private void configure(Bootstrap b) { b.option(ChannelOption.TCP_NODELAY, config.getTcpNoDelay()); b.option(ChannelOption.SO_KEEPALIVE, config.getKeepAlive()); b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.getConnectionTimeout()); }
From source file:com.zextras.modules.chat.server.xmpp.netty.ChatXmppService.java
License:Open Source License
private ServerBootstrap buildBoostrap(EventLoopGroup acceptorGroup, EventLoopGroup workerGroup, final SSLContext zimbraSSLContext, final boolean oldSSL) { ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(acceptorGroup, workerGroup); serverBootstrap.channel(NioServerSocketChannel.class); ChannelHandler handler = new ChannelInitializer<SocketChannel>() { @Override/*from ww w. j a v a 2 s . c o m*/ public void initChannel(SocketChannel ch) throws Exception { try { if (oldSSL) { final SSLEngine engine = zimbraSSLContext.createSSLEngine(); engine.setUseClientMode(false); ch.pipeline().addFirst(null, "SSL", new SslHandler(engine, false)); } ch.pipeline().addLast(null, "SubTagTokenizer", new XmlSubTagTokenizer()); FirstTags firstTagsHandler = new FirstTags(mXmppHandlerFactory, mEventManager, ch, mSchemaProvider, zimbraSSLContext, oldSSL, mChatProperties, mNettyService, mProxyAuthRequestEncoder, mXmppEventFilter, mXmppFilterOut); ch.pipeline().addAfter("SubTagTokenizer", "FirstTags", firstTagsHandler); } catch (Throwable ex) { ChatLog.log.warn("Unable to initialize XMPP connection: " + Utils.exceptionToString(ex)); ch.close(); } } }; serverBootstrap.childHandler(handler).option(ChannelOption.SO_BACKLOG, 128) .childOption(ChannelOption.SO_KEEPALIVE, true).childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 0); return serverBootstrap; }
From source file:com.zextras.modules.chat.services.LocalXmppService.java
License:Open Source License
@Override public void run() { ChatLog.log.info("Listening on port " + DEFAULT_LOCAL_XMPP_PORT); EventLoopGroup acceptorGroup = new NioEventLoopGroup(4); EventLoopGroup channelWorkerGroup = new NioEventLoopGroup(8); Channel channel;//from w w w . ja v a 2 s.c o m try { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(acceptorGroup, channelWorkerGroup); bootstrap.channel(NioServerSocketChannel.class); ChannelHandler handler = new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { try { SSLEngine sslEngine = mZimbraSSLContextProvider.get().createSSLEngine(); sslEngine.setUseClientMode(false); SslHandler sslHandler = new SslHandler(sslEngine); ch.pipeline().addFirst("ssl", sslHandler); ch.pipeline().addLast(null, "SubTagTokenizer", new XmlSubTagTokenizer()); ch.pipeline().addLast(null, "XmlTagTokenizer", new XmlTagTokenizer()); ch.pipeline().addAfter("XmlTagTokenizer", "StanzaProcessor", new ChannelInboundHandlerAdapter() { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { mLocalXmppReceiver.processStanza((String) msg); } }); } catch (Throwable t) { ChatLog.log.warn("Unable to initializer XMPP connection: " + Utils.exceptionToString(t)); ch.close(); } } }; ChannelFuture channelFuture = bootstrap.childHandler(handler).option(ChannelOption.SO_BACKLOG, 128) .childOption(ChannelOption.SO_KEEPALIVE, true) .childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 0).bind(DEFAULT_LOCAL_XMPP_PORT).sync(); if (!channelFuture.isSuccess()) { throw channelFuture.cause(); } channel = channelFuture.channel(); mInitializationPromise.setSuccess(null); } catch (Throwable e) { mInitializationPromise.setFailure(e); return; } mLock.lock(); try { while (!mStopRequested) { try { mWaitStopRequest.await(); } catch (InterruptedException ignored) { } } channel.close().sync(); acceptorGroup.shutdownGracefully().sync(); channelWorkerGroup.shutdownGracefully().sync(); } catch (InterruptedException ignored) { } finally { mLock.unlock(); } }
From source file:darks.grid.network.GridMessageClient.java
License:Apache License
@Override public boolean initialize() { super.initialize(); try {//from w w w . j a v a 2s . c om log.info("Initialize message client."); NetworkConfig config = GridRuntime.config().getNetworkConfig(); int workerNum = config.getClientWorkerThreadNumber(); workerGroup = new NioEventLoopGroup(workerNum, ThreadUtils.getThreadFactory()); bootstrap = new Bootstrap(); bootstrap.group(workerGroup).channel(NioSocketChannel.class) .option(ChannelOption.TCP_NODELAY, config.isTcpNodelay()) .option(ChannelOption.SO_KEEPALIVE, config.isTcpKeepAlive()) .option(ChannelOption.ALLOCATOR, new PooledByteBufAllocator(true)) // .option(ChannelOption.SO_TIMEOUT, config.getRecvTimeout()) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.getConnectTimeout()) .option(ChannelOption.SO_SNDBUF, config.getTcpSendBufferSize()) .option(ChannelOption.SO_RCVBUF, config.getTcpRecvBufferSize()); bootstrap.handler(newChannelHandler()); return true; } catch (Exception e) { log.error(e.getMessage(), e); return false; } }
From source file:darks.grid.network.GridMessageServer.java
License:Apache License
@Override public boolean initialize() { try {// w w w . j ava2 s .c om NetworkConfig config = GridRuntime.config().getNetworkConfig(); int bossNum = Runtime.getRuntime().availableProcessors() * config.getServerBossThreadDelta(); int workerNum = config.getServerWorkerThreadNumber(); bossGroup = new NioEventLoopGroup(bossNum); workerGroup = new NioEventLoopGroup(workerNum); super.initialize(); bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .option(ChannelOption.TCP_NODELAY, config.isTcpNodelay()) .option(ChannelOption.SO_KEEPALIVE, config.isTcpKeepAlive()) .option(ChannelOption.ALLOCATOR, new PooledByteBufAllocator(true)) // .option(ChannelOption.SO_TIMEOUT, config.getRecvTimeout()) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.getConnectTimeout()) .option(ChannelOption.SO_REUSEADDR, config.isTcpReuseAddr()) // .option(ChannelOption.SO_BACKLOG, config.getTcpBacklog()) .option(ChannelOption.SO_SNDBUF, config.getTcpSendBufferSize()) .option(ChannelOption.SO_RCVBUF, config.getTcpRecvBufferSize()) .childOption(ChannelOption.TCP_NODELAY, config.isTcpNodelay()) .childOption(ChannelOption.SO_KEEPALIVE, config.isTcpKeepAlive()) .childOption(ChannelOption.ALLOCATOR, new PooledByteBufAllocator(true)) .childOption(ChannelOption.SO_TIMEOUT, config.getRecvTimeout()) .childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.getConnectTimeout()) .childOption(ChannelOption.SO_REUSEADDR, config.isTcpReuseAddr()) .childOption(ChannelOption.SO_BACKLOG, config.getTcpBacklog()) .childOption(ChannelOption.SO_SNDBUF, config.getTcpSendBufferSize()) .childOption(ChannelOption.SO_RCVBUF, config.getTcpRecvBufferSize()); bootstrap.childHandler(newChannelHandler()); return true; } catch (Exception e) { log.error(e.getMessage(), e); return false; } }
From source file:dbseer.middleware.client.MiddlewareClient.java
License:Apache License
public void run() { // debug info Log.debug(String.format("host = %s", host)); Log.debug(String.format("port = %d", port)); Log.debug(String.format("log path = %s", logPath)); // client needs to handle incoming messages from the middleware as well. EventLoopGroup group = new NioEventLoopGroup(4); try {//from w w w . j av a2s .c o m // attach shutdown hook. MiddlewareClientShutdown shutdownThread = new MiddlewareClientShutdown(this); Runtime.getRuntime().addShutdownHook(shutdownThread); File logDir = new File(logPath); if (!logDir.exists()) { logDir.mkdirs(); } final MiddlewareClient client = this; Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast(new IdleStateHandler(10, 0, 0)); p.addLast(ZlibCodecFactory.newZlibEncoder(ZlibWrapper.ZLIB)); p.addLast(ZlibCodecFactory.newZlibDecoder(ZlibWrapper.ZLIB)); p.addLast(new MiddlewarePacketDecoder()); p.addLast(new MiddlewarePacketEncoder()); p.addLast(new MiddlewareClientHandler(client)); } }); ChannelFuture f = b.connect(host, port).sync(); channel = f.channel(); Log.debug("Connected to the middleware."); MiddlewarePacket checkPacket = new MiddlewarePacket(MiddlewareConstants.PACKET_CHECK_VERSION, MiddlewareConstants.PROTOCOL_VERSION); // ByteBuf buf = Unpooled.buffer(); // buf.writeInt(MiddlewareConstants.PACKET_CHECK_VERSION); // buf.writeInt(MiddlewareConstants.PROTOCOL_VERSION.getBytes("UTF-8").length); // buf.writeBytes(MiddlewareConstants.PROTOCOL_VERSION.getBytes("UTF-8")); // channel.writeAndFlush(buf); channel.writeAndFlush(checkPacket); channel.closeFuture().sync(); } catch (Exception e) { if (e instanceof InterruptedException) { } else { setChanged(); notifyObservers(new MiddlewareClientEvent(MiddlewareClientEvent.ERROR, e)); } Log.error(e.getMessage()); e.printStackTrace(); } finally { group.shutdownGracefully(); this.stopExecutors(); if (txLogFileRaw.exists()) { txLogFileRaw.delete(); } if (txZipOutputStream != null) { try { txZipOutputStream.closeEntry(); txZipOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } txZipOutputStream = null; } } }