List of usage examples for io.netty.channel ChannelOption SO_KEEPALIVE
ChannelOption SO_KEEPALIVE
To view the source code for io.netty.channel ChannelOption SO_KEEPALIVE.
Click Source Link
From source file:bftsmart.communication.client.netty.NettyClientServerCommunicationSystemClientSide.java
License:Apache License
/** * Tulio Ribeiro Connect to specific replica and returns the ChannelFuture. * sessionClientToReplica is replaced with the new connection. Removed redundant * code.// www .j a v a2 s. c om */ public synchronized ChannelFuture connectToReplica(int replicaId, SecretKeyFactory fac) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException { String str = this.clientId + ":" + replicaId; PBEKeySpec spec = TOMUtil.generateKeySpec(str.toCharArray()); SecretKey authKey = fac.generateSecret(spec); Bootstrap b = new Bootstrap(); b.group(workerGroup); b.channel(NioSocketChannel.class); b.option(ChannelOption.SO_KEEPALIVE, true); b.option(ChannelOption.TCP_NODELAY, true); b.option(ChannelOption.SO_SNDBUF, tcpSendBufferSize); b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectionTimeoutMsec); b.handler(getChannelInitializer()); ChannelFuture channelFuture = b.connect(controller.getRemoteAddress(replicaId)); NettyClientServerSession ncss = new NettyClientServerSession(channelFuture.channel(), replicaId); sessionClientToReplica.put(replicaId, ncss); return channelFuture; }
From source file:bftsmart.communication.client.netty.NettyClientServerCommunicationSystemServerSide.java
License:Apache License
public NettyClientServerCommunicationSystemServerSide(ServerViewController controller) { try {//from ww w.j ava 2s .c om this.controller = controller; /* Tulio Ribeiro */ privKey = controller.getStaticConf().getPrivateKey(); sessionReplicaToClient = new ConcurrentHashMap<>(); rl = new ReentrantReadWriteLock(); // Configure the server. serverPipelineFactory = new NettyServerPipelineFactory(this, sessionReplicaToClient, controller, rl); EventLoopGroup bossGroup = new NioEventLoopGroup(bossThreads); EventLoopGroup workerGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors()); ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .option(ChannelOption.SO_REUSEADDR, true).option(ChannelOption.SO_KEEPALIVE, true) .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_SNDBUF, tcpSendBufferSize) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectionTimeoutMsec) .option(ChannelOption.SO_BACKLOG, connectionBacklog) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(serverPipelineFactory.getDecoder()); ch.pipeline().addLast(serverPipelineFactory.getEncoder()); ch.pipeline().addLast(serverPipelineFactory.getHandler()); } }).childOption(ChannelOption.SO_KEEPALIVE, true).childOption(ChannelOption.TCP_NODELAY, true); String myAddress; String confAddress = controller.getStaticConf() .getRemoteAddress(controller.getStaticConf().getProcessId()).getAddress().getHostAddress(); if (InetAddress.getLoopbackAddress().getHostAddress().equals(confAddress)) { myAddress = InetAddress.getLoopbackAddress().getHostAddress(); } else if (controller.getStaticConf().getBindAddress().equals("")) { myAddress = InetAddress.getLocalHost().getHostAddress(); // If Netty binds to the loopback address, clients will not be able to connect // to replicas. // To solve that issue, we bind to the address supplied in config/hosts.config // instead. if (InetAddress.getLoopbackAddress().getHostAddress().equals(myAddress) && !myAddress.equals(confAddress)) { myAddress = confAddress; } } else { myAddress = controller.getStaticConf().getBindAddress(); } int myPort = controller.getStaticConf().getPort(controller.getStaticConf().getProcessId()); ChannelFuture f = b.bind(new InetSocketAddress(myAddress, myPort)).sync(); logger.info("ID = " + controller.getStaticConf().getProcessId()); logger.info("N = " + controller.getCurrentViewN()); logger.info("F = " + controller.getCurrentViewF()); logger.info("Port (client <-> server) = " + controller.getStaticConf().getPort(controller.getStaticConf().getProcessId())); logger.info("Port (server <-> server) = " + controller.getStaticConf().getServerToServerPort(controller.getStaticConf().getProcessId())); logger.info("requestTimeout = " + controller.getStaticConf().getRequestTimeout()); logger.info("maxBatch = " + controller.getStaticConf().getMaxBatchSize()); if (controller.getStaticConf().getUseSignatures() == 1) logger.info("Using Signatures"); else if (controller.getStaticConf().getUseSignatures() == 2) logger.info("Using benchmark signature verification"); logger.info("Binded replica to IP address " + myAddress); // ******* EDUARDO END **************// /* Tulio Ribeiro */ // SSL/TLS logger.info("SSL/TLS enabled, protocol version: {}", controller.getStaticConf().getSSLTLSProtocolVersion()); /* Tulio Ribeiro END */ mainChannel = f.channel(); } catch (InterruptedException | UnknownHostException ex) { logger.error("Failed to create Netty communication system", ex); } }
From source file:blazingcache.network.netty.NettyChannelAcceptor.java
License:Apache License
public void start() throws Exception { if (ssl) {/*from w w w . j a v a 2s .c o m*/ if (sslCertFile == null) { LOGGER.log(Level.SEVERE, "start SSL with self-signed auto-generated certificate"); if (sslCiphers != null) { LOGGER.log(Level.SEVERE, "required sslCiphers " + sslCiphers); } SelfSignedCertificate ssc = new SelfSignedCertificate(); try { sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).ciphers(sslCiphers) .build(); } finally { ssc.delete(); } } else { LOGGER.log(Level.SEVERE, "start SSL with certificate " + sslCertFile.getAbsolutePath() + " chain file " + sslCertChainFile.getAbsolutePath()); if (sslCiphers != null) { LOGGER.log(Level.SEVERE, "required sslCiphers " + sslCiphers); } sslCtx = SslContextBuilder.forServer(sslCertChainFile, sslCertFile, sslCertPassword) .ciphers(sslCiphers).build(); } } if (callbackThreads == 0) { callbackExecutor = Executors.newCachedThreadPool(); } else { callbackExecutor = Executors.newFixedThreadPool(callbackThreads, new ThreadFactory() { private final AtomicLong count = new AtomicLong(); @Override public Thread newThread(Runnable r) { return new Thread(r, "blazingcache-callbacks-" + count.incrementAndGet()); } }); } bossGroup = new NioEventLoopGroup(workerThreads); workerGroup = new NioEventLoopGroup(workerThreads); ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { NettyChannel session = new NettyChannel("unnamed", ch, callbackExecutor, null); if (acceptor != null) { acceptor.createConnection(session); } // ch.pipeline().addLast(new LoggingHandler()); // Add SSL handler first to encrypt and decrypt everything. if (ssl) { ch.pipeline().addLast(sslCtx.newHandler(ch.alloc())); } ch.pipeline().addLast("lengthprepender", new LengthFieldPrepender(4)); ch.pipeline().addLast("lengthbaseddecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4)); // ch.pipeline().addLast("messageencoder", new DataMessageEncoder()); ch.pipeline().addLast("messagedecoder", new DataMessageDecoder()); ch.pipeline().addLast(new InboundMessageHandler(session)); } }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true); ChannelFuture f = b.bind(host, port).sync(); // (7) this.channel = f.channel(); }
From source file:cc.agentx.client.net.nio.XConnectHandler.java
License:Apache License
@Override public void channelRead0(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception { boolean proxyMode = isAgentXNeeded(request.host()); log.info("\tClient -> Proxy \tTarget {}:{} [{}]", request.host(), request.port(), proxyMode ? "AGENTX" : "DIRECT"); Promise<Channel> promise = ctx.executor().newPromise(); promise.addListener(new FutureListener<Channel>() { @Override//from ww w .j a v a2s . c o m 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(channelFuture -> { ByteBuf byteBuf = Unpooled.buffer(); request.encodeAsByteBuf(byteBuf); if (byteBuf.hasArray()) { byte[] xRequestBytes = new byte[byteBuf.readableBytes()]; byteBuf.getBytes(0, xRequestBytes); if (proxyMode) { // handshaking to remote proxy xRequestBytes = requestWrapper.wrap(xRequestBytes); outboundChannel.writeAndFlush(Unpooled.wrappedBuffer( exposeRequest ? xRequestBytes : wrapper.wrap(xRequestBytes))); } // task handover ReferenceCountUtil.retain(request); // auto-release? a trap? ctx.pipeline().remove(XConnectHandler.this); outboundChannel.pipeline().addLast(new XRelayHandler(ctx.channel(), proxyMode ? wrapper : rawWrapper, false)); ctx.pipeline().addLast(new XRelayHandler(outboundChannel, proxyMode ? wrapper : rawWrapper, true)); } }); } else { ctx.channel() .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType())); if (ctx.channel().isActive()) { ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } } } }); String host = request.host(); int port = request.port(); if (host.equals(config.getConsoleDomain())) { host = "localhost"; port = config.getConsolePort(); } else if (proxyMode) { host = config.getServerHost(); port = config.getServerPort(); } // ping target bootstrap.group(ctx.channel().eventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true) .handler(new XPingHandler(promise, System.currentTimeMillis())).connect(host, port) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { ctx.channel().writeAndFlush( new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType())); if (ctx.channel().isActive()) { ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } } } }); }
From source file:cc.agentx.server.net.nio.XConnectHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { try {/*www. jav a 2 s .co m*/ ByteBuf byteBuf = (ByteBuf) msg; if (!byteBuf.hasArray()) { byte[] bytes = new byte[byteBuf.readableBytes()]; byteBuf.getBytes(0, bytes); if (!requestParsed) { if (!exposedRequest) { bytes = wrapper.unwrap(bytes); if (bytes == null) { log.info("\tClient -> Proxy \tHalf Request"); return; } } XRequest xRequest = requestWrapper.parse(bytes); String host = xRequest.getHost(); int port = xRequest.getPort(); int dataLength = xRequest.getSubsequentDataLength(); if (dataLength > 0) { byte[] tailData = Arrays.copyOfRange(bytes, bytes.length - dataLength, bytes.length); if (exposedRequest) { tailData = wrapper.unwrap(tailData); if (tailData != null) { tailDataBuffer.write(tailData, 0, tailData.length); } } else { tailDataBuffer.write(tailData, 0, tailData.length); } } log.info("\tClient -> Proxy \tTarget {}:{}{}", host, port, DnsCache.isCached(host) ? " [Cached]" : ""); if (xRequest.getAtyp() == XRequest.Type.DOMAIN) { try { host = DnsCache.get(host); if (host == null) { host = xRequest.getHost(); } } catch (UnknownHostException e) { log.warn("\tClient <- Proxy \tBad DNS! ({})", e.getMessage()); ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); return; } } 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()) { // handle tail byte[] tailData = tailDataBuffer.toByteArray(); tailDataBuffer.close(); if (tailData.length > 0) { log.info("\tClient ==========> Target \tSend Tail [{} bytes]", tailData.length); } outboundChannel .writeAndFlush((tailData.length > 0) ? Unpooled.wrappedBuffer(tailData) : Unpooled.EMPTY_BUFFER) .addListener(channelFuture -> { // task handover outboundChannel.pipeline() .addLast(new XRelayHandler(ctx.channel(), wrapper, false)); ctx.pipeline() .addLast(new XRelayHandler(outboundChannel, wrapper, true)); ctx.pipeline().remove(XConnectHandler.this); }); } else { if (ctx.channel().isActive()) { ctx.writeAndFlush(Unpooled.EMPTY_BUFFER) .addListener(ChannelFutureListener.CLOSE); } } } }); final String finalHost = host; bootstrap.group(ctx.channel().eventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000) .option(ChannelOption.SO_KEEPALIVE, true) .handler(new XPingHandler(promise, System.currentTimeMillis())).connect(host, port) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { if (ctx.channel().isActive()) { log.warn("\tClient <- Proxy \tBad Ping! ({}:{})", finalHost, port); ctx.writeAndFlush(Unpooled.EMPTY_BUFFER) .addListener(ChannelFutureListener.CLOSE); } } } }); requestParsed = true; } else { bytes = wrapper.unwrap(bytes); if (bytes != null) tailDataBuffer.write(bytes, 0, bytes.length); } } } finally { ReferenceCountUtil.release(msg); } }
From source file:cc.ly.mc.client.netty.SocketClient.java
License:Apache License
public void run() { // Configure the server. worker = new OioEventLoopGroup(); Bootstrap b = new Bootstrap(); b.group(worker).channel(OioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true) .option(ChannelOption.SO_REUSEADDR, true).handler(new SocketClientInitializer()); // Start the client. channel = b.connect(host, port).channel(); }
From source file:cc.ly.mc.core.client.io.SocketClient.java
License:Apache License
public void run() { // Configure the server. worker = new OioEventLoopGroup(); Bootstrap b = new Bootstrap(); b.group(worker).channel(OioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true) .option(ChannelOption.SO_REUSEADDR, true) .handler(new SocketClientInitializer(connectedListeners, disconnectedListeners)); // Start the client. channel = b.connect(host, port).channel(); }
From source file:ccwihr.client.t2.Http2Client.java
License:Apache License
public static void main(String[] args) throws Exception { // // Configure SSL. // final SslContext sslCtx; // if (SSL) { // SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK; // sslCtx = SslContextBuilder.forClient() // .sslProvider(provider) // /* NOTE: the cipher filter may not include all ciphers required by the HTTP/2 specification. // * Please refer to the HTTP/2 specification for cipher requirements. */ // .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) // .trustManager(InsecureTrustManagerFactory.INSTANCE) // .applicationProtocolConfig(new ApplicationProtocolConfig( // Protocol.ALPN, // // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers. // SelectorFailureBehavior.NO_ADVERTISE, // // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers. // SelectedListenerFailureBehavior.ACCEPT, // ApplicationProtocolNames.HTTP_2, // ApplicationProtocolNames.HTTP_1_1)) // .build(); // } else { // sslCtx = null; // }/* ww w. j a va 2 s . co m*/ EventLoopGroup workerGroup = new NioEventLoopGroup(); // Http2ClientInitializer initializer = new Http2ClientInitializer(sslCtx, Integer.MAX_VALUE); Http2ClientInitializer initializer = new Http2ClientInitializer(null, Integer.MAX_VALUE); try { // Configure the client. Bootstrap b = new Bootstrap(); b.group(workerGroup); b.channel(NioSocketChannel.class); b.option(ChannelOption.SO_KEEPALIVE, true); b.remoteAddress(HOST, PORT); b.handler(initializer); // Start the client. Channel channel = b.connect().syncUninterruptibly().channel(); System.out.println("Connected to [" + HOST + ':' + PORT + ']'); // Wait for the HTTP/2 upgrade to occur. Http2SettingsHandler http2SettingsHandler = initializer.settingsHandler(); http2SettingsHandler.awaitSettings(5, TimeUnit.SECONDS); HttpResponseHandler responseHandler = initializer.responseHandler(); int streamId = 3; HttpScheme scheme = SSL ? HttpScheme.HTTPS : HttpScheme.HTTP; AsciiString hostName = new AsciiString(HOST + ':' + PORT); System.err.println("Sending request(s)..."); if (URL != null) { // Create a simple GET request. FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET, URL); request.headers().add(HttpHeaderNames.HOST, hostName); request.headers().add(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), scheme.name()); request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP); request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE); responseHandler.put(streamId, channel.writeAndFlush(request), channel.newPromise()); streamId += 2; } if (URL2 != null) { // Create a simple POST request with a body. FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, POST, URL2, Unpooled.copiedBuffer(URL2DATA.getBytes(CharsetUtil.UTF_8))); request.headers().add(HttpHeaderNames.HOST, hostName); request.headers().add(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), scheme.name()); request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP); request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE); responseHandler.put(streamId, channel.writeAndFlush(request), channel.newPromise()); streamId += 2; } responseHandler.awaitResponses(5, TimeUnit.SECONDS); System.out.println("Finished HTTP/2 request(s)"); // Wait until the connection is closed. channel.close().syncUninterruptibly(); } finally { workerGroup.shutdownGracefully(); } }
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 w w . j a v a 2 s .c om 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:com.addthis.meshy.Meshy.java
License:Apache License
protected Meshy() { if (HOSTNAME != null) { uuid = HOSTNAME + "-" + Long.toHexString(System.currentTimeMillis() & 0xffffff); } else {//from w ww . j a va2 s .c o m 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(); }