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:com.spotify.ffwd.protocol.ProtocolClientsImpl.java
License:Apache License
private AsyncFuture<ProtocolConnection> connectTCP(Logger log, Protocol protocol, ProtocolClient client, RetryPolicy policy) {//from www. jav a2 s . co m final Bootstrap b = new Bootstrap(); b.group(worker); b.channel(NioSocketChannel.class); b.handler(client.initializer()); b.option(ChannelOption.SO_KEEPALIVE, true); final String host = protocol.getAddress().getHostString(); final int port = protocol.getAddress().getPort(); final ProtocolConnection connection = new RetryingProtocolConnection(async, timer, log, policy, new ProtocolChannelSetup() { @Override public ChannelFuture setup() { return b.connect(host, port); } @Override public String toString() { return String.format("connect tcp://%s:%d", host, port); } }); return async.resolved(connection); }
From source file:com.spotify.ffwd.protocol.ProtocolServersImpl.java
License:Apache License
private AsyncFuture<ProtocolConnection> bindTCP(final Logger log, final Protocol protocol, ProtocolServer server, RetryPolicy policy) { final ServerBootstrap b = new ServerBootstrap(); b.group(boss, worker);/*ww w . jav a2s . c o m*/ b.channel(NioServerSocketChannel.class); b.childHandler(server.initializer()); b.option(ChannelOption.SO_BACKLOG, 128); if (protocol.getReceiveBufferSize() != null) { b.childOption(ChannelOption.SO_RCVBUF, protocol.getReceiveBufferSize()); } b.childOption(ChannelOption.SO_KEEPALIVE, true); final String host = protocol.getAddress().getHostString(); final int port = protocol.getAddress().getPort(); final RetryingProtocolConnection connection = new RetryingProtocolConnection(async, timer, log, policy, new ProtocolChannelSetup() { @Override public ChannelFuture setup() { return b.bind(host, port); } @Override public String toString() { return String.format("bind tcp://%s:%d", host, port); } }); return connection.getInitialFuture(); }
From source file:com.springapp.mvc.netty.example.spdy.client.SpdyClient.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE) .applicationProtocolConfig(//from www .java 2 s .c o m new ApplicationProtocolConfig(Protocol.NPN, SelectorFailureBehavior.CHOOSE_MY_LAST_PROTOCOL, SelectedListenerFailureBehavior.CHOOSE_MY_LAST_PROTOCOL, SelectedProtocol.SPDY_3_1.protocolName(), SelectedProtocol.HTTP_1_1.protocolName())) .build(); HttpResponseClientHandler httpResponseHandler = new HttpResponseClientHandler(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { 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:com.streamsets.pipeline.stage.origin.tcp.TCPConsumingServer.java
License:Apache License
@Override protected AbstractBootstrap bootstrap(boolean enableEpoll) { if (enableEpoll) { enableDirectBuffers();/* w w w.j ava 2s. c o m*/ // boss group simply opens channels and hands processing off to the child EpollEventLoopGroup bossGroup = new EpollEventLoopGroup(NUM_BOSS_THREADS); EventLoopGroup workerGroup = new EpollEventLoopGroup(numThreads); groups.add(bossGroup); groups.add(workerGroup); ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(EpollServerSocketChannel.class) .childHandler(this.channelInitializer) .option(ChannelOption.SO_BACKLOG, SOCKET_MAX_INBOUND_CONNECTION_QUEUE_DEPTH) .childOption(ChannelOption.SO_KEEPALIVE, SOCKET_KEEPALIVE); return b; } else { disableDirectBuffers(); EventLoopGroup bossGroup = new NioEventLoopGroup(NUM_BOSS_THREADS); EventLoopGroup workerGroup = new NioEventLoopGroup(numThreads); groups.add(bossGroup); groups.add(workerGroup); ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(this.channelInitializer) .option(ChannelOption.SO_BACKLOG, SOCKET_MAX_INBOUND_CONNECTION_QUEUE_DEPTH) .childOption(ChannelOption.SO_KEEPALIVE, SOCKET_KEEPALIVE); return b; } }
From source file:com.streamsets.pipeline.stage.origin.tcp.TestTCPServerSource.java
License:Apache License
private ChannelFuture startTcpClient(TCPServerSourceConfig configBean, EventLoopGroup workerGroup, byte[] data, boolean randomlySlice) throws InterruptedException { ChannelFuture channelFuture;//from w ww. jav a 2 s. com Bootstrap bootstrap = new Bootstrap(); bootstrap.group(workerGroup); bootstrap.channel(NioSocketChannel.class); bootstrap.option(ChannelOption.SO_KEEPALIVE, true); bootstrap.handler(new ChannelInitializer() { @Override protected void initChannel(Channel ch) throws Exception { ch.pipeline().addLast(new TCPServerSourceClientHandler(randomlySlice, data)); } }); // Start the client. channelFuture = bootstrap.connect("localhost", Integer.parseInt(configBean.ports.get(0))).sync(); return channelFuture; }
From source file:com.stremebase.examples.todomvc.Todo.java
License:Apache License
public static void main(String[] args) throws Exception { css = new String(Files.readAllBytes(Paths.get(System.getProperty("user.dir"), "Web", "index.css"))); favicon = Files.readAllBytes(Paths.get(System.getProperty("user.dir"), "Web", "favicon.ico")); Table.setDefaultDb(new DB("user.dir")); data = new Data(itemTableId, "ITEMTABLE"); @SuppressWarnings("unchecked") Router<Integer> router = new Router<Integer>().GET("/", GET).GET("/filter/:filtertype", FILTER) .POST("/", POST).POST("/delete", DELETE).POST("/clearcompleted", DELETECOMPLETED) .POST("/toggle-status", TOGGLESTATUS) .GET(":something/index.css", CSS).GET("/index.css", CSS).GET("/favicon.ico", ICON) .notFound(NOTFOUND);//from ww w. j a v a 2 s. c om System.out.println(router); OioEventLoopGroup bossGroup = new OioEventLoopGroup(1); SingleThreadEventLoop workerGroup = new ThreadPerChannelEventLoop(bossGroup); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).childOption(ChannelOption.TCP_NODELAY, java.lang.Boolean.TRUE) .childOption(ChannelOption.SO_KEEPALIVE, java.lang.Boolean.TRUE) .childOption(ChannelOption.SO_REUSEADDR, java.lang.Boolean.TRUE) .channel(OioServerSocketChannel.class).childHandler(new HttpRouterServerInitializer(router)); Channel ch = b.bind(PORT).sync().channel(); System.out.println("Server started: http://127.0.0.1:" + PORT + '/'); ch.closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:com.system.distribute.server.FileClient.java
License:Apache License
public ChannelFuture run() throws Exception { // Configure the server. final Bootstrap bootstrap = BootstrapFactory.createBootstrap(ChannelType.NIO); bootstrap.handler(new FileClientHandler()); bootstrap.option(ChannelOption.TCP_NODELAY, true); bootstrap.option(ChannelOption.SO_KEEPALIVE, true); bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000); try {//from w w w .j a v a2s . co m final ChannelFuture channelFuture = bootstrap.connect(new InetSocketAddress(host, port)).sync(); channelFuture.awaitUninterruptibly(); } catch (InterruptedException e) { } // Start the server. ChannelFuture f = bootstrap.bind(port).sync(); // Wait until the server socket is closed. f.channel().closeFuture().sync(); return f; }
From source file:com.tencent.mars.proxy.ProxyServer.java
License:Open Source License
public void start() throws Exception { try {//from www .j a v a 2s .co m serverBootstrap = new ServerBootstrap(); serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(channelHandler).option(ChannelOption.SO_BACKLOG, 128) .childOption(ChannelOption.SO_KEEPALIVE, true); ChannelFuture channelFuture = serverBootstrap.bind(port).sync(); channelFuture.channel().closeFuture().sync(); } catch (Exception e) { } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } }
From source file:com.tesora.dve.db.mysql.portal.MySqlPortal.java
License:Open Source License
public MySqlPortal(Properties props) throws PEException { // This is the port the Portal is going to listen on - // default to Mysql's port int port = Singletons.require(HostService.class).getPortalPort(props); Singletons.replace(MySqlPortalService.class, this); InternalLoggerFactory.setDefaultFactory(new Log4JLoggerFactory()); int max_concurrent = KnownVariables.MAX_CONCURRENT.getValue(null).intValue(); //TODO: parse/plan is on this pool, which is probably ok, especially with blocking calls to catalog. Check for responses that can be done by backend netty threads and avoid two context shifts. clientExecutorService = new PEThreadPoolExecutor(max_concurrent, max_concurrent, 30L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), //The thread count limits concurrency here. Using a bounded queue here would block netty threads (very bad), so this pool could be overrun by 'bad' clients that pipeline. -sgossard new PEDefaultThreadFactory("msp-client")); clientExecutorService.allowCoreThreadTimeOut(true); bossGroup = new NioEventLoopGroup(1, new PEDefaultThreadFactory("msp-boss")); //fixes the number of Netty NIO threads to the number of available CPUs. workerGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors(), new PEDefaultThreadFactory("netty-worker")); ServerBootstrap b = new ServerBootstrap(); try {/*from ww w . ja v a2 s .co m*/ b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { if (PACKET_LOGGER) ch.pipeline().addFirst(new LoggingHandler(LogLevel.INFO)); ch.pipeline() .addLast(MSPProtocolDecoder.class.getSimpleName(), new MSPProtocolDecoder( MSPProtocolDecoder.MyDecoderState.READ_CLIENT_AUTH)) .addLast(new MSPAuthenticateHandlerV10()) .addLast(MSPCommandHandler.class.getSimpleName(), new MSPCommandHandler(clientExecutorService)) .addLast(ConnectionHandlerAdapter.getInstance()); } }) .childOption(ChannelOption.ALLOCATOR, USE_POOLED_BUFFERS ? PooledByteBufAllocator.DEFAULT : UnpooledByteBufAllocator.DEFAULT) .childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true) .bind(port).sync(); logger.info("DVE Server bound to port " + port); } catch (Exception e) { throw new PEException("Failed to bind DVE server to port " + port + " - " + e.getMessage(), e); } }
From source file:com.thomas.netty4.SimpleEchoServer.java
License:Apache License
public static void main(String[] args) throws Exception { System.out.println("PORT"); if (args.length > 0) { PORT = Integer.parseInt(args[0]); }//from w w w.jav a2s . c o m // Configure SSL. final SslContext sslCtx; if (SSL) { SelfSignedCertificate ssc = new SelfSignedCertificate(); sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build(); } else { sslCtx = null; } // Configure the server. EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) // .option(ChannelOption.SO_BACKLOG, 100) .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_KEEPALIVE, true) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); if (sslCtx != null) { p.addLast(sslCtx.newHandler(ch.alloc())); } // p.addLast(new LoggingHandler(LogLevel.INFO)); p.addLast(new SimpleEchoServerHandler()); } }); // Start the server. ChannelFuture f = b.bind(PORT).sync(); // Wait until the server socket is closed. f.channel().closeFuture().sync(); } finally { // Shut down all event loops to terminate all threads. bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }