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:http2.client.Http2Client.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) {/*w ww . ja va2 s . c o m*/ 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; } EventLoopGroup workerGroup = new NioEventLoopGroup(); Http2ClientInitializer initializer = new Http2ClientInitializer(sslCtx, 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 (URL2 != null) { logger.info("send url2"); // 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:io.advantageous.conekt.http.impl.HttpClientImpl.java
License:Open Source License
private void applyConnectionOptions(Bootstrap bootstrap) { bootstrap.option(ChannelOption.TCP_NODELAY, options.isTcpNoDelay()); if (options.getSendBufferSize() != -1) { bootstrap.option(ChannelOption.SO_SNDBUF, options.getSendBufferSize()); }//from w ww . j ava2s . co m if (options.getReceiveBufferSize() != -1) { bootstrap.option(ChannelOption.SO_RCVBUF, options.getReceiveBufferSize()); bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(options.getReceiveBufferSize())); } if (options.getSoLinger() != -1) { bootstrap.option(ChannelOption.SO_LINGER, options.getSoLinger()); } if (options.getTrafficClass() != -1) { bootstrap.option(ChannelOption.IP_TOS, options.getTrafficClass()); } bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, options.getConnectTimeout()); bootstrap.option(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE); bootstrap.option(ChannelOption.SO_KEEPALIVE, options.isTcpKeepAlive()); bootstrap.option(ChannelOption.SO_REUSEADDR, options.isReuseAddress()); }
From source file:io.advantageous.conekt.http.impl.HttpServerImpl.java
License:Open Source License
private void applyConnectionOptions(ServerBootstrap bootstrap) { bootstrap.childOption(ChannelOption.TCP_NODELAY, options.isTcpNoDelay()); if (options.getSendBufferSize() != -1) { bootstrap.childOption(ChannelOption.SO_SNDBUF, options.getSendBufferSize()); }//w w w .j a va2 s . co m if (options.getReceiveBufferSize() != -1) { bootstrap.childOption(ChannelOption.SO_RCVBUF, options.getReceiveBufferSize()); bootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(options.getReceiveBufferSize())); } if (options.getSoLinger() != -1) { bootstrap.option(ChannelOption.SO_LINGER, options.getSoLinger()); } if (options.getTrafficClass() != -1) { bootstrap.childOption(ChannelOption.IP_TOS, options.getTrafficClass()); } bootstrap.childOption(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE); bootstrap.childOption(ChannelOption.SO_KEEPALIVE, options.isTcpKeepAlive()); bootstrap.option(ChannelOption.SO_REUSEADDR, options.isReuseAddress()); if (options.getAcceptBacklog() != -1) { bootstrap.option(ChannelOption.SO_BACKLOG, options.getAcceptBacklog()); } }
From source file:io.advantageous.conekt.net.impl.NetClientImpl.java
License:Open Source License
private void applyConnectionOptions(Bootstrap bootstrap) { bootstrap.option(ChannelOption.TCP_NODELAY, options.isTcpNoDelay()); if (options.getSendBufferSize() != -1) { bootstrap.option(ChannelOption.SO_SNDBUF, options.getSendBufferSize()); }//from w w w . j av a2 s . c om if (options.getReceiveBufferSize() != -1) { bootstrap.option(ChannelOption.SO_RCVBUF, options.getReceiveBufferSize()); bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(options.getReceiveBufferSize())); } if (options.getSoLinger() != -1) { bootstrap.option(ChannelOption.SO_LINGER, options.getSoLinger()); } if (options.getTrafficClass() != -1) { bootstrap.option(ChannelOption.IP_TOS, options.getTrafficClass()); } bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, options.getConnectTimeout()); bootstrap.option(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE); bootstrap.option(ChannelOption.SO_KEEPALIVE, options.isTcpKeepAlive()); }
From source file:io.advantageous.conekt.net.impl.NetServerImpl.java
License:Open Source License
private void applyConnectionOptions(ServerBootstrap bootstrap) { bootstrap.childOption(ChannelOption.TCP_NODELAY, options.isTcpNoDelay()); if (options.getSendBufferSize() != -1) { bootstrap.childOption(ChannelOption.SO_SNDBUF, options.getSendBufferSize()); }/*from w w w.j av a 2s .c o m*/ if (options.getReceiveBufferSize() != -1) { bootstrap.childOption(ChannelOption.SO_RCVBUF, options.getReceiveBufferSize()); bootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(options.getReceiveBufferSize())); } if (options.getSoLinger() != -1) { bootstrap.option(ChannelOption.SO_LINGER, options.getSoLinger()); } if (options.getTrafficClass() != -1) { bootstrap.childOption(ChannelOption.IP_TOS, options.getTrafficClass()); } bootstrap.childOption(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE); bootstrap.childOption(ChannelOption.SO_KEEPALIVE, options.isTcpKeepAlive()); bootstrap.option(ChannelOption.SO_REUSEADDR, options.isReuseAddress()); if (options.getAcceptBacklog() != -1) { bootstrap.option(ChannelOption.SO_BACKLOG, options.getAcceptBacklog()); } }
From source file:io.aos.netty5.http2.client.Http2Client.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) {/*from ww w . j a va 2s .c o m*/ sslCtx = SslContext.newClientContext(null, InsecureTrustManagerFactory.INSTANCE, null, Arrays.asList(SelectedProtocol.HTTP_2.protocolName(), SelectedProtocol.HTTP_1_1.protocolName()), 0, 0); } else { sslCtx = null; } EventLoopGroup workerGroup = new NioEventLoopGroup(); Http2ClientInitializer initializer = new Http2ClientInitializer(sslCtx, 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; URI hostName = URI.create((SSL ? "https" : "http") + "://" + 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(HttpHeaders.Names.HOST, hostName); request.headers().add(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP); channel.writeAndFlush(request); responseHandler.put(streamId, 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(HttpHeaders.Names.HOST, hostName); request.headers().add(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP); channel.writeAndFlush(request); responseHandler.put(streamId, 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:io.aos.netty5.socksproxy.SocksServerConnectHandler.java
License:Apache License
@Override public void messageReceived(final ChannelHandlerContext ctx, final SocksRequest message) throws Exception { if (message instanceof Socks4CmdRequest) { final Socks4CmdRequest request = (Socks4CmdRequest) message; Promise<Channel> promise = ctx.executor().newPromise(); promise.addListener(new GenericFutureListener<Future<Channel>>() { @Override/*ww w.jav a 2 s .c o m*/ public void operationComplete(final Future<Channel> future) throws Exception { final Channel outboundChannel = future.getNow(); if (future.isSuccess()) { ctx.channel().writeAndFlush(new Socks4CmdResponse(Socks4CmdStatus.SUCCESS)) .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 Socks4CmdResponse(Socks4CmdStatus.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.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 Socks4CmdResponse(Socks4CmdStatus.REJECTED_OR_FAILED)); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); } else if (message instanceof Socks5CmdRequest) { final Socks5CmdRequest request = (Socks5CmdRequest) message; Promise<Channel> promise = ctx.executor().newPromise(); promise.addListener(new GenericFutureListener<Future<Channel>>() { @Override public void operationComplete(final Future<Channel> future) throws Exception { final Channel outboundChannel = future.getNow(); if (future.isSuccess()) { ctx.channel() .writeAndFlush( new Socks5CmdResponse(Socks5CmdStatus.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 Socks5CmdResponse(Socks5CmdStatus.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 Socks5CmdResponse(Socks5CmdStatus.FAILURE, request.addressType())); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); } else { ctx.close(); } }
From source file:io.aos.netty5.spdy.client.SpdyClient.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx = SslContext.newClientContext(null, InsecureTrustManagerFactory.INSTANCE, null, IdentityCipherSuiteFilter.INSTANCE, Arrays.asList(SelectedProtocol.SPDY_3_1.protocolName(), SelectedProtocol.HTTP_1_1.protocolName()), JettyNpnSslEngineWrapper.instance(), 0, 0); HttpResponseClientHandler httpResponseHandler = new HttpResponseClientHandler(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try {// w w w. j av a2 s. c om Bootstrap b = new Bootstrap(); b.group(workerGroup); b.channel(NioSocketChannel.class); b.option(ChannelOption.SO_KEEPALIVE, true); b.remoteAddress(HOST, PORT); b.handler(new SpdyClientInitializer(sslCtx, httpResponseHandler)); // Start the client. Channel channel = b.connect().syncUninterruptibly().channel(); System.out.println("Connected to " + HOST + ':' + PORT); // Create a GET request. HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, ""); request.headers().set(HttpHeaders.Names.HOST, HOST); request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP); // Send the GET request. channel.writeAndFlush(request).sync(); // Waits for the complete HTTP response httpResponseHandler.queue().take().sync(); System.out.println("Finished SPDY HTTP GET"); // Wait until the connection is closed. channel.close().syncUninterruptibly(); } finally { if (workerGroup != null) { workerGroup.shutdownGracefully(); } } }
From source file:io.atomix.catalyst.transport.netty.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(transport.eventLoopGroup()).channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override//from ww w. j a v a 2s . c o m protected void initChannel(SocketChannel channel) throws Exception { ChannelPipeline pipeline = channel.pipeline(); if (transport.properties().sslEnabled()) { pipeline.addFirst( new SslHandler(new NettyTls(transport.properties()).initSslEngine(true))); } pipeline.addLast(FIELD_PREPENDER); pipeline.addLast(new LengthFieldBasedFrameDecoder(transport.properties().maxFrameSize(), 0, 4, 0, 4)); pipeline.addLast( new NettyHandler(connections, future::complete, context, transport.properties())); } }); bootstrap.option(ChannelOption.TCP_NODELAY, transport.properties().tcpNoDelay()); bootstrap.option(ChannelOption.SO_KEEPALIVE, transport.properties().tcpKeepAlive()); bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, transport.properties().connectTimeout()); bootstrap.option(ChannelOption.ALLOCATOR, ALLOCATOR); if (transport.properties().sendBufferSize() != -1) { bootstrap.option(ChannelOption.SO_SNDBUF, transport.properties().sendBufferSize()); } if (transport.properties().receiveBufferSize() != -1) { bootstrap.option(ChannelOption.SO_RCVBUF, transport.properties().receiveBufferSize()); } 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.catalyst.transport.netty.NettyServer.java
License:Apache License
/** * Starts listening for the given member. *//*w ww . j a va2 s. c om*/ private void listen(Address address, Consumer<Connection> listener, ThreadContext context) { channelGroup = new DefaultChannelGroup("catalyst-acceptor-channels", GlobalEventExecutor.INSTANCE); handler = new ServerHandler(connections, listener, context, transport.properties()); final ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(transport.eventLoopGroup()).channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.DEBUG)).childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel channel) throws Exception { ChannelPipeline pipeline = channel.pipeline(); if (transport.properties().sslEnabled()) { pipeline.addFirst( new SslHandler(new NettyTls(transport.properties()).initSslEngine(false))); } pipeline.addLast(FIELD_PREPENDER); pipeline.addLast(new LengthFieldBasedFrameDecoder(transport.properties().maxFrameSize(), 0, 4, 0, 4)); pipeline.addLast(handler); } }).option(ChannelOption.SO_BACKLOG, transport.properties().acceptBacklog()) .option(ChannelOption.TCP_NODELAY, transport.properties().tcpNoDelay()) .option(ChannelOption.SO_REUSEADDR, transport.properties().reuseAddress()) .childOption(ChannelOption.ALLOCATOR, ALLOCATOR) .childOption(ChannelOption.SO_KEEPALIVE, transport.properties().tcpKeepAlive()); if (transport.properties().sendBufferSize() != -1) { bootstrap.childOption(ChannelOption.SO_SNDBUF, transport.properties().sendBufferSize()); } if (transport.properties().receiveBufferSize() != -1) { bootstrap.childOption(ChannelOption.SO_RCVBUF, transport.properties().receiveBufferSize()); } LOGGER.info("Binding to {}", address); ChannelFuture bindFuture = bootstrap.bind(address.socketAddress()); bindFuture.addListener((ChannelFutureListener) channelFuture -> { if (channelFuture.isSuccess()) { listening = true; context.executor().execute(() -> { LOGGER.info("Listening at {}", bindFuture.channel().localAddress()); listenFuture.complete(null); }); } else { context.execute(() -> listenFuture.completeExceptionally(channelFuture.cause())); } }); channelGroup.add(bindFuture.channel()); }