List of usage examples for io.netty.bootstrap ServerBootstrap childOption
public <T> ServerBootstrap childOption(ChannelOption<T> childOption, T value)
From source file:org.wenxueliu.netty.client.ClientTest.java
License:Apache License
/** * Accepts incoming connections.//from www . j av a 2s .co m */ private void startAcceptingConnections() throws InterruptedException { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new CommunicationChannelInitializer()); b.option(ChannelOption.SO_BACKLOG, 128); b.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024); b.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024); b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); b.childOption(ChannelOption.SO_KEEPALIVE, true); b.bind(80).sync(); }
From source file:org.wso2.carbon.protobuf.registry.internal.ProtobufRegistryActivator.java
License:Open Source License
public void start(BundleContext bundleContext) { log.info("/////////////////////////////////////"); // load protobuf server configurations from pbs xml ProtobufConfiguration configuration = null; try {//from w w w . j av a2 s . com configuration = ProtobufConfigFactory.build(); } catch (ProtobufConfigurationException e) { String msg = "Error while loading pbs xml file " + e.getLocalizedMessage(); log.error(msg, e); return; } if (!configuration.isEnabled()) { log.debug("ProtobufServer is not enabled in pbs xml"); return; } log.info("Starting ProtobufServer..."); // gathering configurations into local variables ServerConfiguration carbonConfig = ServerConfiguration.getInstance(); org.wso2.carbon.protobuf.registry.config.ServerConfiguration serverConfig = configuration .getServerConfiguration(); ServerCallExecutorThreadPoolConfiguration callExecutorConfig = serverConfig .getServerCallExecutorThreadPoolConfiguration(); TimeoutExecutorThreadPoolConfiguration timeoutExecutorConfig = serverConfig .getTimeoutExecutorThreadPoolConfiguration(); TimeoutCheckerThreadPoolConfiguration timeoutCheckerConfig = serverConfig .getTimeoutCheckerThreadPoolConfiguration(); LoggerConfiguration loggerConfig = serverConfig.getLoggerConfiguration(); TransportConfiguration transportConfig = configuration.getTransportConfiguration(); AcceptorsConfiguration acceptorsConfig = transportConfig.getAcceptorsConfiguration(); ChannelHandlersConfiguration channelHandlersConfig = transportConfig.getChannelHandlersConfiguration(); String hostName = carbonConfig.getFirstProperty("HostName"); int port = serverConfig.getPort(); int portOffset = Integer.parseInt(carbonConfig.getFirstProperty("Ports.Offset")); int effectivePort = port + portOffset; // server information PeerInfo serverInfo = new PeerInfo(hostName, effectivePort); int callExecutorCorePoolSize = callExecutorConfig.getCorePoolSize(); int callExecutorMaxPoolSize = callExecutorConfig.getMaxPoolSize(); int callExecutorMaxPoolTimeout = callExecutorConfig.getMaxPoolTimeout(); int callExecutorWorkQueueCapacity = callExecutorConfig.getWorkQueueCapacity(); // call executor RpcServerCallExecutor callExecutor = new ThreadPoolCallExecutor(callExecutorCorePoolSize, callExecutorMaxPoolSize, callExecutorMaxPoolTimeout, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(callExecutorWorkQueueCapacity), Executors.defaultThreadFactory()); serverFactory = new DuplexTcpServerPipelineFactory(serverInfo); serverFactory.setRpcServerCallExecutor(callExecutor); // if SSL encryption is enabled if (serverConfig.isSSLEnabled()) { //read keystore and truststore from carbon String keystorePassword = carbonConfig.getFirstProperty("Security.KeyStore.Password"); String keystorePath = carbonConfig.getFirstProperty("Security.KeyStore.Location"); String truststorePassword = carbonConfig.getFirstProperty("Security.TrustStore.Password"); String truststorePath = carbonConfig.getFirstProperty("Security.TrustStore.Location"); RpcSSLContext sslCtx = new RpcSSLContext(); sslCtx.setKeystorePassword(keystorePassword); sslCtx.setKeystorePath(keystorePath); sslCtx.setTruststorePassword(truststorePassword); sslCtx.setTruststorePath(truststorePath); try { sslCtx.init(); } catch (Exception e) { String msg = "Couldn't create SSL Context : " + e.getLocalizedMessage(); log.error(msg, e); return; } serverFactory.setSslContext(sslCtx); } // Timeout Executor int timeoutExecutorCorePoolSize = timeoutExecutorConfig.getCorePoolSize(); int timeoutExecutorMaxPoolSize = timeoutExecutorConfig.getMaxPoolSize(); int timeoutExecutorKeepAliveTime = timeoutExecutorConfig.getKeepAliveTime(); BlockingQueue<Runnable> timeoutExecutorWorkQueue = new ArrayBlockingQueue<Runnable>( timeoutExecutorCorePoolSize, false); ThreadFactory timeoutExecutorTF = new RenamingThreadFactoryProxy("timeout", Executors.defaultThreadFactory()); RpcTimeoutExecutor timeoutExecutor = new TimeoutExecutor(timeoutExecutorCorePoolSize, timeoutExecutorMaxPoolSize, timeoutExecutorKeepAliveTime, TimeUnit.SECONDS, timeoutExecutorWorkQueue, timeoutExecutorTF); // Timeout Checker int timeoutCheckerSleepTimeMs = timeoutCheckerConfig.getPeriod(); int timeoutCheckerCorePoolSize = timeoutCheckerConfig.getCorePoolSize(); ThreadFactory timeoutCheckerTF = new RenamingThreadFactoryProxy("check", Executors.defaultThreadFactory()); RpcTimeoutChecker timeoutChecker = new TimeoutChecker(timeoutCheckerSleepTimeMs, timeoutCheckerCorePoolSize, timeoutCheckerTF); timeoutChecker.setTimeoutExecutor(timeoutExecutor); timeoutChecker.startChecking(serverFactory.getRpcClientRegistry()); // setup a RPC event listener - it just logs what happens RpcConnectionEventNotifier rpcEventNotifier = new RpcConnectionEventNotifier(); RpcConnectionEventListener listener = new RpcConnectionEventListener() { @Override public void connectionReestablished(RpcClientChannel clientChannel) { log.info("Protobuf connection Reestablished " + clientChannel); } @Override public void connectionOpened(RpcClientChannel clientChannel) { log.info("Protobuf connection Opened " + clientChannel); } @Override public void connectionLost(RpcClientChannel clientChannel) { log.info("Protobuf connection Lost " + clientChannel); } @Override public void connectionChanged(RpcClientChannel clientChannel) { log.info("Protobuf connection Changed " + clientChannel); } }; rpcEventNotifier.setEventListener(listener); serverFactory.registerConnectionEventListener(rpcEventNotifier); // ProtobufServer Logger boolean isLogReq = loggerConfig.isLogReqProtoEnabled(); boolean isLogRes = loggerConfig.isLogResProtoEnabled(); boolean isLogEve = loggerConfig.isLogEventProtoEnabled(); CategoryPerServiceLogger logger = new CategoryPerServiceLogger(); logger.setLogRequestProto(isLogReq); logger.setLogResponseProto(isLogRes); logger.setLogEventProto(isLogEve); if (isLogReq || isLogRes || isLogEve) { serverFactory.setLogger(logger); } else { serverFactory.setLogger(null); } // Call acceptors parameters int acceptorsPoolSize = acceptorsConfig.getPoolSize(); int acceptorsSendBufferSize = acceptorsConfig.getSendBufferSize(); int acceptorsReceiverBufferSize = acceptorsConfig.getReceiverBufferSize(); // Channel handlers parameters int channelHandlersPoolSize = channelHandlersConfig.getPoolSize(); int channelHandlersSendBufferSize = channelHandlersConfig.getSendBufferSize(); int channelHandlersReceiverBufferSize = channelHandlersConfig.getReceiverBufferSize(); // enable nagle's algorithm or not boolean tcpNoDelay = transportConfig.isTCPNoDelay(); // boss and worker thread factories ThreadFactory bossTF = new RenamingThreadFactoryProxy("boss", Executors.defaultThreadFactory()); NioEventLoopGroup boss = new NioEventLoopGroup(acceptorsPoolSize, bossTF); ThreadFactory workersTF = new RenamingThreadFactoryProxy("worker", Executors.defaultThreadFactory()); NioEventLoopGroup workers = new NioEventLoopGroup(channelHandlersPoolSize, workersTF); // Configure the server. ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(boss, workers); bootstrap.channel(NioServerSocketChannel.class); bootstrap.option(ChannelOption.SO_SNDBUF, acceptorsSendBufferSize); bootstrap.option(ChannelOption.SO_RCVBUF, acceptorsReceiverBufferSize); bootstrap.childOption(ChannelOption.SO_RCVBUF, channelHandlersReceiverBufferSize); bootstrap.childOption(ChannelOption.SO_SNDBUF, channelHandlersSendBufferSize); bootstrap.option(ChannelOption.TCP_NODELAY, tcpNoDelay); bootstrap.childHandler(serverFactory); bootstrap.localAddress(serverInfo.getPort()); // To release resources on shutdown CleanShutdownHandler shutdownHandler = new CleanShutdownHandler(); shutdownHandler.addResource(boss); shutdownHandler.addResource(workers); shutdownHandler.addResource(callExecutor); shutdownHandler.addResource(timeoutChecker); shutdownHandler.addResource(timeoutExecutor); // Bind and start to accept incoming connections. bootstrap.bind(); log.info("ProtobufServer Serving " + serverInfo); // Register ProtobufServer Registry as an OSGi service ProtobufRegistry pbsRegistry = new ProtobufRegistryImpl(serverFactory); bundleContext.registerService(ProtobufRegistry.class.getName(), pbsRegistry, null); }
From source file:org.wso2.carbon.transport.http.netty.util.server.HttpServer.java
License:Open Source License
/** * Start the HttpServer/*from ww w.java 2 s . c om*/ */ public void start() { bossGroup = new NioEventLoopGroup(this.bossGroupSize); workerGroup = new NioEventLoopGroup(this.workerGroupSize); try { ServerBootstrap b = new ServerBootstrap(); b.option(ChannelOption.SO_BACKLOG, 100); b.childOption(ChannelOption.TCP_NODELAY, true); b.option(ChannelOption.SO_KEEPALIVE, true); b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 15000); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(channelInitializer); ChannelFuture ch = b.bind(new InetSocketAddress(TestUtil.TEST_HOST, port)); ch.sync(); logger.info("HttpServer started on port " + port); } catch (InterruptedException e) { logger.error("HTTP Server cannot start on port " + port); } }
From source file:org.wso2.carbon.transport.http.netty.util.server.HttpsServer.java
License:Open Source License
/** * Start the HttpsServer/*from w w w .j a va 2s .c o m*/ */ public void start() { bossGroup = new NioEventLoopGroup(this.bossGroupSize); workerGroup = new NioEventLoopGroup(this.workerGroupSize); try { ServerBootstrap b = new ServerBootstrap(); b.option(ChannelOption.SO_BACKLOG, 100); b.childOption(ChannelOption.TCP_NODELAY, true); b.option(ChannelOption.SO_KEEPALIVE, true); b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 15000); KeyStore ks = KeyStore.getInstance("JKS"); ks.load(new FileInputStream(ksName), ksPass); KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(ks, ctPass); sslContext = SSLContext.getInstance("TLS"); sslContext.init(kmf.getKeyManagers(), null, null); ((HTTPServerInitializer) channelInitializer).setSslContext(sslContext); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(channelInitializer); ChannelFuture ch = b.bind(new InetSocketAddress(TestUtil.TEST_HOST, port)); ch.sync(); logger.info("HttpServer started on port " + port); } catch (Exception e) { logger.error("HTTP Server cannot start on port " + port); } }
From source file:org.wso2.siddhi.extension.input.transport.http.server.HTTPServer.java
License:Open Source License
/** * Start the HTTPServer/*from w w w. j av a2 s . c o m*/ */ public void start() { bossGroup = new NioEventLoopGroup(this.bossGroupSize); workerGroup = new NioEventLoopGroup(this.workerGroupSize); try { ServerBootstrap b = new ServerBootstrap(); b.option(ChannelOption.SO_BACKLOG, backLog); b.childOption(ChannelOption.TCP_NODELAY, tcpNoDelay); b.option(ChannelOption.SO_KEEPALIVE, isKeepAlive); b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectionTimeOut); httpServerInitializer = new HTTPServerInitializer(); httpServerInitializer.setSslContext(sslContext); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(httpServerInitializer); ChannelFuture ch = b.bind(new InetSocketAddress(ServerUtil.TEST_HOST, port)).sync(); logger.info("HTTPServer starting on port " + port); if (ch.isSuccess()) { logger.info("HTTPServer started on port " + port); } } catch (InterruptedException e) { logger.error("HTTP Server cannot start on port " + port); } }
From source file:org.xwiki.contrib.websocket.internal.NettyWebSocketService.java
License:Open Source License
private void initialize0() throws Exception { final SslContext sslCtx; if (this.conf.sslEnabled()) { if (this.conf.getCertChainFilename() != null) { // They provided a cert chain filename (and ostensibly a private key) // ssl w/ CA signed certificate. final File certChain = new File(this.conf.getCertChainFilename()); final File privKey = new File(this.conf.getPrivateKeyFilename()); checkCertChainAndPrivKey(certChain, privKey); sslCtx = SslContext.newServerContext(certChain, privKey); } else {/*from ww w. ja v a2 s . c om*/ // SSL enabled but no certificate specified, lets use a selfie this.logger.warn("websocket.ssl.enable = true but websocket.ssl.certChainFile " + "is unspecified, generating a Self Signed Certificate."); SelfSignedCertificate ssc = new SelfSignedCertificate(); sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey()); } } else { sslCtx = null; } final EventLoopGroup bossGroup = new NioEventLoopGroup(1); final EventLoopGroup workerGroup = new NioEventLoopGroup(); ServerBootstrap b = new ServerBootstrap(); // get rid of silly lag b.childOption(ChannelOption.TCP_NODELAY, Boolean.TRUE); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new WebSocketServerInitializer(sslCtx, this)); Channel ch = b.bind(this.conf.getBindTo(), this.conf.getPort()).sync().channel(); ch.closeFuture().addListener(new GenericFutureListener<ChannelFuture>() { public void operationComplete(ChannelFuture f) { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }); }
From source file:p2p_server.P2p_server.java
public void run() throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); List<ChannelFuture> futures = new ArrayList<>(); SelfSignedCertificate ssc = new SelfSignedCertificate(); SslContext sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build(); try {// w w w .j a v a 2s . c o m ServerBootstrap appboot = new ServerBootstrap(); appboot.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 8192).childHandler(new AppChildChannelHandler(sslCtx)); appboot.option(ChannelOption.SO_REUSEADDR, true); appboot.option(ChannelOption.TCP_NODELAY, true); appboot.childOption(ChannelOption.SO_KEEPALIVE, true); appboot.childOption(ChannelOption.SO_RCVBUF, 512); appboot.childOption(ChannelOption.SO_SNDBUF, 512); ServerBootstrap devboot = new ServerBootstrap(); devboot.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 8192).childHandler(new DevChildChannelHandler(sslCtx)); devboot.option(ChannelOption.SO_REUSEADDR, true); devboot.option(ChannelOption.TCP_NODELAY, true); devboot.childOption(ChannelOption.SO_KEEPALIVE, true); devboot.childOption(ChannelOption.SO_RCVBUF, 512); devboot.childOption(ChannelOption.SO_SNDBUF, 512); //ChannelFuture f = boostrap.bind(port).sync(); futures.add(devboot.bind(5560)); futures.add(appboot.bind(5561)); for (ChannelFuture f : futures) { f.sync(); } for (ChannelFuture f : futures) { f.channel().closeFuture().sync(); } // ??? // f.channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:playground.gregor.vis.VisServer.java
License:Open Source License
private void initServer() { PeerInfo server = new PeerInfo("localhost", 9090); RpcServerCallExecutor executor = new ThreadPoolCallExecutor(3, 200); DuplexTcpServerPipelineFactory serverFactory = new DuplexTcpServerPipelineFactory(server); serverFactory.setRpcServerCallExecutor(executor); ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(/*from ww w . j ava 2 s . com*/ new NioEventLoopGroup(0, new RenamingThreadFactoryProxy("boss", Executors.defaultThreadFactory())), new NioEventLoopGroup(0, new RenamingThreadFactoryProxy("worker", Executors.defaultThreadFactory()))); bootstrap.channel(NioServerSocketChannel.class); bootstrap.childHandler(serverFactory); bootstrap.localAddress(server.getPort()); bootstrap.option(ChannelOption.SO_SNDBUF, 1048576); bootstrap.option(ChannelOption.SO_RCVBUF, 1048576); bootstrap.childOption(ChannelOption.SO_RCVBUF, 1048576); bootstrap.childOption(ChannelOption.SO_SNDBUF, 1048576); bootstrap.option(ChannelOption.TCP_NODELAY, true); serverFactory.getRpcServiceRegistry() .registerService(ProtoFrame.FrameServerService.newReflectiveBlockingService(this.service)); bootstrap.bind(); }
From source file:ratpack.server.internal.DefaultRatpackServer.java
License:Apache License
protected Channel buildChannel(final ServerConfig serverConfig, final ChannelHandler handlerAdapter) throws InterruptedException { SslContext sslContext = serverConfig.getNettySslContext(); this.useSsl = sslContext != null; ServerBootstrap serverBootstrap = new ServerBootstrap(); serverConfig.getConnectTimeoutMillis().ifPresent(i -> { serverBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, i); serverBootstrap.childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, i); });// w w w.jav a 2s. com serverConfig.getMaxMessagesPerRead().ifPresent(i -> { FixedRecvByteBufAllocator allocator = new FixedRecvByteBufAllocator(i); serverBootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, allocator); serverBootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, allocator); }); serverConfig.getReceiveBufferSize().ifPresent(i -> { serverBootstrap.option(ChannelOption.SO_RCVBUF, i); serverBootstrap.childOption(ChannelOption.SO_RCVBUF, i); }); serverConfig.getWriteSpinCount().ifPresent(i -> { serverBootstrap.option(ChannelOption.WRITE_SPIN_COUNT, i); serverBootstrap.childOption(ChannelOption.WRITE_SPIN_COUNT, i); }); serverConfig.getConnectQueueSize().ifPresent(i -> serverBootstrap.option(ChannelOption.SO_BACKLOG, i)); return serverBootstrap.group(execController.getEventLoopGroup()) .channel(ChannelImplDetector.getServerSocketChannelImpl()) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); new ConnectionIdleTimeout(pipeline, serverConfig.getIdleTimeout()); if (sslContext != null) { SSLEngine sslEngine = sslContext.newEngine(PooledByteBufAllocator.DEFAULT); pipeline.addLast("ssl", new SslHandler(sslEngine)); } pipeline.addLast("decoder", new HttpRequestDecoder(serverConfig.getMaxInitialLineLength(), serverConfig.getMaxHeaderSize(), serverConfig.getMaxChunkSize(), false)); pipeline.addLast("encoder", new HttpResponseEncoder()); pipeline.addLast("deflater", new IgnorableHttpContentCompressor()); pipeline.addLast("chunkedWriter", new ChunkedWriteHandler()); pipeline.addLast("adapter", handlerAdapter); ch.config().setAutoRead(false); } }).bind(buildSocketAddress(serverConfig)).sync().channel(); }
From source file:sailfish.remoting.DefaultServer.java
License:Apache License
private ServerBootstrap newServerBootstrap() { ServerBootstrap serverBoot = new ServerBootstrap(); serverBoot.channel(NettyPlatformIndependent.serverChannelClass()); // connections wait for accept serverBoot.option(ChannelOption.SO_BACKLOG, 1024); serverBoot.option(ChannelOption.SO_REUSEADDR, true); // replace by heart beat serverBoot.childOption(ChannelOption.SO_KEEPALIVE, false); serverBoot.childOption(ChannelOption.TCP_NODELAY, true); serverBoot.childOption(ChannelOption.SO_SNDBUF, 32 * 1024); serverBoot.childOption(ChannelOption.SO_RCVBUF, 32 * 1024); // temporary settings, need more tests serverBoot.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(8 * 1024, 32 * 1024)); serverBoot.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); //default is true, reduce thread context switching serverBoot.childOption(ChannelOption.SINGLE_EVENTEXECUTOR_PER_GROUP, true); return serverBoot; }