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:net.hasor.rsf.bootstrap.RsfBootstrap.java
License:Apache License
public RsfContext sync() throws Throwable { LoggerHelper.logInfo("initialize rsfBootstrap"); if (this.rsfStart == null) { LoggerHelper.logInfo("create RsfStart."); this.rsfStart = new InnerRsfStart(); }// w w w. j a v a 2 s . c o m if (this.settings == null) { this.settings = new DefaultRsfSettings(new StandardContextSettings(DEFAULT_RSF_CONFIG)); this.settings.refresh(); } if (this.settings.getXmlNode("hasor.rsfConfig") == null) { throw new IOException("settings is not load."); } // //RsfContext LoggerHelper.logInfo("agent shutdown method on DefaultRsfContext.", DEFAULT_RSF_CONFIG); final DefaultRsfContext rsfContext = new DefaultRsfContext(this.settings) { public void shutdown() { LoggerHelper.logInfo("shutdown rsf."); super.shutdown(); doShutdown(); } }; if (this.workMode == WorkMode.Customer) { return doBinder(rsfContext); } // //localAddress & bindSocket InetAddress localAddress = this.localAddress; if (localAddress == null) { localAddress = finalBindAddress(rsfContext); } int bindSocket = (this.bindSocket < 1) ? this.settings.getBindPort() : this.bindSocket; LoggerHelper.logInfo("bind to address = %s , port = %s.", localAddress, bindSocket); //Netty final URL hostAddress = URLUtils.toURL(localAddress.getHostAddress(), bindSocket); final NioEventLoopGroup bossGroup = new NioEventLoopGroup(this.settings.getNetworkListener(), new NameThreadFactory("RSF-Listen-%s")); ServerBootstrap boot = new ServerBootstrap(); boot.group(bossGroup, rsfContext.getLoopGroup()); boot.channel(NioServerSocketChannel.class); boot.childHandler(new ChannelInitializer<SocketChannel>() { public void initChannel(SocketChannel ch) throws Exception { Channel channel = ch.pipeline().channel(); NetworkConnection.initConnection(hostAddress, channel); // ch.pipeline().addLast(new RSFCodec(), new RsfProviderHandler(rsfContext)); } }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true); ChannelFuture future = boot.bind(localAddress, bindSocket); final Channel serverChannel = future.channel(); LoggerHelper.logInfo("rsf Server started at :%s:%s", localAddress, bindSocket); //add this.shutdownHook = new Runnable() { public void run() { LoggerHelper.logInfo("shutdown rsf server."); bossGroup.shutdownGracefully(); serverChannel.close(); } }; // return doBinder(rsfContext); }
From source file:net.hasor.rsf.center.server.launcher.http.HttpClient.java
License:Apache License
public BasicFuture<HttpResponse> request(String requestPath, Map<String, String> reqParams, byte[] body) throws Exception { // ?Netty/* w w w .j a v a 2 s . com*/ final Bootstrap b = new Bootstrap(); final BasicFuture<HttpResponse> future = new BasicFuture<HttpResponse>(); b.group(this.worker); b.channel(NioSocketChannel.class); b.option(ChannelOption.SO_KEEPALIVE, true); b.handler(new ChannelInitializer<SocketChannel>() { public void initChannel(SocketChannel ch) throws Exception { // httpResponse??HttpResponseDecoder? ch.pipeline().addLast(new HttpResponseDecoder()); // ??httprequest?HttpRequestEncoder? ch.pipeline().addLast(new HttpRequestEncoder()); ch.pipeline().addLast(new ResponseRead(future)); } }); // // Server ChannelFuture f = b.connect(this.remoteHost, this.remotePort).sync(); // // http URL reqPath = new URL("http", this.remoteHost, this.remotePort, requestPath); DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, reqPath.toString()); request.headers().set(HttpHeaders.Names.HOST, this.remoteHost); request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE); request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, request.content().readableBytes()); // // ??http if (body != null) { request.content().writeBytes(body); } f.channel().write(request); f.channel().flush(); // // f.channel().closeFuture().addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture nettyFuture) throws Exception { future.cancel();//? } }); return future; }
From source file:net.hasor.rsf.remoting.transport.customer.InnerClientManager.java
License:Apache License
private synchronized AbstractRsfClient connSocket(final Address hostAddress) { final URL hostURL = hostAddress.getAddress(); Bootstrap boot = new Bootstrap(); boot.group(this.rsfContext.getLoopGroup()); boot.channel(NioSocketChannel.class); boot.option(ChannelOption.SO_KEEPALIVE, true); boot.handler(new ChannelInitializer<SocketChannel>() { public void initChannel(SocketChannel ch) throws Exception { Channel channel = ch.pipeline().channel(); NetworkConnection.initConnection(hostURL, channel); LoggerHelper.logInfo("initConnection connect %s.", hostURL); ///*from w w w. ja va 2s .c o m*/ ch.pipeline().addLast(new RSFCodec(), new InnerRsfCustomerHandler(getRequestManager())); } }); ChannelFuture future = null; SocketAddress remote = new InetSocketAddress(hostURL.getHost(), hostURL.getPort()); LoggerHelper.logInfo("connect to %s ...", hostURL); future = boot.connect(remote); try { future.await(); } catch (InterruptedException e) { LoggerHelper.logSevere("connect to %s failure , %s", hostURL, e.getMessage()); return null; } if (future.isSuccess() == true) { LoggerHelper.logInfo("remote %s connected.", hostURL); NetworkConnection conn = NetworkConnection.getConnection(future.channel()); return new InnerRsfClient(this.getRequestManager(), conn); } // try { LoggerHelper.logSevere("connect to %s failure , %s", hostURL, future.cause().getMessage()); future.channel().close().await(); } catch (InterruptedException e) { LoggerHelper.logSevere("close connect(%s) failure , %s", hostURL, e.getMessage()); } return null; }
From source file:net.hasor.rsf.rpc.net.Connector.java
License:Apache License
/** * ??/*from w ww. j a v a 2s .c om*/ * @param listenLoopGroup ? */ public void startListener(NioEventLoopGroup listenLoopGroup) { // ServerBootstrap boot = new ServerBootstrap(); boot.group(listenLoopGroup, this.workLoopGroup); boot.channel(NioServerSocketChannel.class); boot.childHandler(new ChannelInitializer<SocketChannel>() { public void initChannel(SocketChannel ch) throws Exception { ChannelHandler[] handlerArrays = channelHandler(); ArrayList<ChannelHandler> handlers = new ArrayList<ChannelHandler>(); handlers.addAll(Arrays.asList(handlerArrays)); // ?? handlers.add(Connector.this); // ?RequestInfo?ResponseInfoRSF // ch.pipeline().addLast(handlers.toArray(new ChannelHandler[handlers.size()])); } }); boot.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); boot.childOption(ChannelOption.SO_KEEPALIVE, true); ChannelFuture future = configBoot(boot).bind(this.bindAddress.toSocketAddress()); // final BasicFuture<RsfChannel> result = new BasicFuture<RsfChannel>(); future.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { future.channel().close(); result.failed(future.cause()); } else { Channel channel = future.channel(); result.completed(new RsfChannel(protocol, bindAddress, channel, LinkType.Listener)); } } }); try { this.localListener = result.get(); logger.info("rsf Server started at {}", this.bindAddress); } catch (Exception e) { logger.error("rsf start listener error: " + e.getMessage(), e); throw new RsfException(ProtocolStatus.NetworkError, this.bindAddress.toString() + " -> " + e.getMessage()); } // }
From source file:net.hasor.rsf.rpc.net.Connector.java
License:Apache License
private <T extends AbstractBootstrap<?, ?>> T configBoot(T boot) { boot.option(ChannelOption.SO_KEEPALIVE, true); // boot.option(ChannelOption.SO_BACKLOG, 128); // boot.option(ChannelOption.SO_BACKLOG, 1024); // boot.option(ChannelOption.SO_RCVBUF, 1024 * 256); // boot.option(ChannelOption.SO_SNDBUF, 1024 * 256); boot.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); return boot;/*from ww w .j ava 2 s . c o m*/ }
From source file:net.jselby.pc.network.NetworkServer.java
License:Open Source License
public void run() { bossGroup = new NioEventLoopGroup(); workerGroup = new NioEventLoopGroup(); try {//from ww w. j a v a2s . com ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new PacketDecoder(), new ClientConnectionHandler()); } }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true); System.out.println("Binding to port " + port + "..."); ChannelFuture fut = b.bind("0.0.0.0", port).sync(); this.f = fut.channel().closeFuture(); } catch (InterruptedException e) { e.printStackTrace(); } finally { } }
From source file:net.kuujo.copycat.io.transport.NettyClient.java
License:Apache License
@Override public CompletableFuture<Connection> connect(Address address) { Assert.notNull(address, "address"); Context context = getContext(); CompletableFuture<Connection> future = new ComposableFuture<>(); LOGGER.info("Connecting to {}", address); Bootstrap bootstrap = new Bootstrap(); bootstrap.group(eventLoopGroup).channel( eventLoopGroup instanceof EpollEventLoopGroup ? EpollSocketChannel.class : NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override/*www .j a v a 2 s. c o m*/ protected void initChannel(SocketChannel channel) throws Exception { ChannelPipeline pipeline = channel.pipeline(); pipeline.addLast(FIELD_PREPENDER); pipeline.addLast(new LengthFieldBasedFrameDecoder(1024 * 32, 0, 2, 0, 2)); pipeline.addLast(new ClientHandler(connections, future::complete, context)); } }); bootstrap.option(ChannelOption.TCP_NODELAY, true); bootstrap.option(ChannelOption.SO_KEEPALIVE, true); bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000); bootstrap.option(ChannelOption.ALLOCATOR, ALLOCATOR); 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:net.kuujo.copycat.io.transport.NettyServer.java
License:Apache License
/** * Starts listening for the given member. *//*from w w w. jav a 2s. c o m*/ private void listen(Address address, Consumer<Connection> listener, Context context) { channelGroup = new DefaultChannelGroup("copycat-acceptor-channels", GlobalEventExecutor.INSTANCE); handler = new ServerHandler(connections, listener, context); final ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(eventLoopGroup) .channel(eventLoopGroup instanceof EpollEventLoopGroup ? EpollServerSocketChannel.class : NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.DEBUG)).childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel channel) throws Exception { ChannelPipeline pipeline = channel.pipeline(); pipeline.addLast(FIELD_PREPENDER); pipeline.addLast(new LengthFieldBasedFrameDecoder(1024 * 32, 0, 2, 0, 2)); pipeline.addLast(handler); } }).option(ChannelOption.SO_BACKLOG, 128).option(ChannelOption.TCP_NODELAY, true) .option(ChannelOption.SO_REUSEADDR, true).childOption(ChannelOption.ALLOCATOR, ALLOCATOR) .childOption(ChannelOption.SO_KEEPALIVE, true); 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()); }
From source file:net.kuujo.copycat.netty.NettyTcpProtocolClient.java
License:Apache License
@Override public CompletableFuture<Void> connect() { final CompletableFuture<Void> future = new CompletableFuture<>(); if (channel != null) { future.complete(null);//from w ww.j a va 2 s . com return future; } final SslContext sslContext; if (protocol.isSsl()) { try { sslContext = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE); } catch (SSLException e) { future.completeExceptionally(e); return future; } } else { sslContext = null; } group = new NioEventLoopGroup(protocol.getThreads()); Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel channel) throws Exception { ChannelPipeline pipeline = channel.pipeline(); if (sslContext != null) { pipeline.addLast(sslContext.newHandler(channel.alloc(), host, port)); } pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(1048576, 0, 4, 0, 4)); pipeline.addLast("bytesDecoder", new ByteArrayDecoder()); pipeline.addLast("frameEncoder", new LengthFieldPrepender(4)); pipeline.addLast("bytesEncoder", new ByteArrayEncoder()); pipeline.addLast("handler", channelHandler); } }); if (protocol.getSendBufferSize() > -1) { bootstrap.option(ChannelOption.SO_SNDBUF, protocol.getSendBufferSize()); } if (protocol.getReceiveBufferSize() > -1) { bootstrap.option(ChannelOption.SO_RCVBUF, protocol.getReceiveBufferSize()); } if (protocol.getTrafficClass() > -1) { bootstrap.option(ChannelOption.IP_TOS, protocol.getTrafficClass()); } bootstrap.option(ChannelOption.TCP_NODELAY, true); bootstrap.option(ChannelOption.SO_LINGER, protocol.getSoLinger()); bootstrap.option(ChannelOption.SO_KEEPALIVE, true); bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, protocol.getConnectTimeout()); bootstrap.connect(host, port).addListener((ChannelFutureListener) channelFuture -> { if (channelFuture.isSuccess()) { channel = channelFuture.channel(); future.complete(null); } else { future.completeExceptionally(channelFuture.cause()); } }); return future; }
From source file:net.kuujo.copycat.netty.NettyTcpProtocolServer.java
License:Apache License
@Override public synchronized CompletableFuture<Void> listen() { final CompletableFuture<Void> future = new CompletableFuture<>(); final SslContext sslContext; if (protocol.isSsl()) { try {//from w ww. ja v a2s. co m SelfSignedCertificate ssc = new SelfSignedCertificate(); sslContext = SslContext.newServerContext(ssc.certificate(), ssc.privateKey()); } catch (SSLException | CertificateException e) { future.completeExceptionally(e); return future; } } else { sslContext = null; } serverGroup = new NioEventLoopGroup(); workerGroup = new NioEventLoopGroup(protocol.getThreads()); final ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(serverGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel channel) throws Exception { ChannelPipeline pipeline = channel.pipeline(); if (sslContext != null) { pipeline.addLast(sslContext.newHandler(channel.alloc())); } pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(1048576, 0, 4, 0, 4)); pipeline.addLast("bytesDecoder", new ByteArrayDecoder()); pipeline.addLast("frameEncoder", new LengthFieldPrepender(4)); pipeline.addLast("bytesEncoder", new ByteArrayEncoder()); pipeline.addLast("handler", new ServerHandler()); } }).option(ChannelOption.SO_BACKLOG, 128); if (protocol.getSendBufferSize() > -1) { bootstrap.option(ChannelOption.SO_SNDBUF, protocol.getSendBufferSize()); } if (protocol.getReceiveBufferSize() > -1) { bootstrap.option(ChannelOption.SO_RCVBUF, protocol.getReceiveBufferSize()); } bootstrap.option(ChannelOption.TCP_NODELAY, true); bootstrap.option(ChannelOption.SO_REUSEADDR, true); bootstrap.option(ChannelOption.SO_KEEPALIVE, true); bootstrap.option(ChannelOption.SO_BACKLOG, protocol.getAcceptBacklog()); if (protocol.getTrafficClass() > -1) { bootstrap.option(ChannelOption.IP_TOS, protocol.getTrafficClass()); } bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true); // Bind and start to accept incoming connections. bootstrap.bind(host, port).addListener((ChannelFutureListener) channelFuture -> { channelFuture.channel().closeFuture().addListener(closeFuture -> { workerGroup.shutdownGracefully(); }); if (channelFuture.isSuccess()) { channel = channelFuture.channel(); future.complete(null); } else { future.completeExceptionally(channelFuture.cause()); } }); return future; }