Java Code Examples for io.netty.bootstrap.ServerBootstrap#group()
The following examples show how to use
io.netty.bootstrap.ServerBootstrap#group() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TcpServerBinder.java From servicetalk with Apache License 2.0 | 6 votes |
private static void configure(ReadOnlyTcpServerConfig config, boolean autoRead, ServerBootstrap bs, @Nullable EventLoopGroup eventLoopGroup, Class<? extends SocketAddress> bindAddressClass) { if (eventLoopGroup == null) { throw new IllegalStateException("IoExecutor must be specified before building"); } bs.group(eventLoopGroup); bs.channel(BuilderUtils.serverChannel(eventLoopGroup, bindAddressClass)); for (@SuppressWarnings("rawtypes") Map.Entry<ChannelOption, Object> opt : config.options().entrySet()) { @SuppressWarnings("unchecked") ChannelOption<Object> option = opt.getKey(); bs.childOption(option, opt.getValue()); } bs.childOption(ChannelOption.AUTO_READ, autoRead); bs.option(ChannelOption.SO_BACKLOG, config.backlog()); // Set the correct ByteBufAllocator based on our BufferAllocator to minimize memory copies. ByteBufAllocator byteBufAllocator = POOLED_ALLOCATOR; bs.option(ChannelOption.ALLOCATOR, byteBufAllocator); bs.childOption(ChannelOption.ALLOCATOR, byteBufAllocator); }
Example 2
Source File: ProxyServer.java From flashback with BSD 2-Clause "Simplified" License | 6 votes |
/** * Start proxy server * */ public void start() throws InterruptedException { ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(_acceptorGroup, _upstreamWorkerGroup); serverBootstrap.channelFactory(new ChannelFactory<ServerChannel>() { @Override public ServerChannel newChannel() { return new NioServerSocketChannel(); } }); serverBootstrap.childHandler(new ProxyInitializer(this)); //bind ChannelFuture future = serverBootstrap.bind(_host, _port); //wait for the future future.awaitUninterruptibly(); if (!future.isSuccess()) { future.channel().closeFuture().awaitUninterruptibly(); throw new ChannelException(String.format("Failed to bind to: %s:%d", _host, _port), future.cause()); } else { _allChannels.add(future.channel()); } }
Example 3
Source File: NettyServer.java From mini-dubbo with GNU General Public License v3.0 | 6 votes |
public void doOpen() throws InterruptedException { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try{ ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(bossGroup,workerGroup); serverBootstrap.channel(NioServerSocketChannel.class); serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() { protected void initChannel(SocketChannel socketChannel) throws Exception { ChannelPipeline pipeline = socketChannel.pipeline(); pipeline.addLast(new ObjectDecoder(1024*1024, ClassResolvers.weakCachingConcurrentResolver(this.getClass().getClassLoader()))); pipeline.addLast(new ObjectEncoder()); pipeline.addLast((SimpleChannelInboundHandler)handler); } }); serverBootstrap.option(ChannelOption.SO_BACKLOG,1024); serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE,true); ChannelFuture future = serverBootstrap.bind(address,port).sync(); //future.channel().closeFuture().sync(); }finally{ //workerGroup.shutdownGracefully(); //bossGroup.shutdownGracefully(); } }
Example 4
Source File: GruffaloProxy.java From gruffalo with Apache License 2.0 | 6 votes |
private ChannelFuture createTcpBootstrap(final TcpServerPipelineFactory tcpServerPipelineFactory, final int tcpPort) throws InterruptedException { log.info("Initializing TCP..."); ServerBootstrap tcpBootstrap = new ServerBootstrap(); tcpBootstrap.group(eventLoopGroup); tcpBootstrap.channel(NioServerSocketChannel.class); tcpBootstrap.childHandler(tcpServerPipelineFactory); tcpBootstrap.option(ChannelOption.ALLOCATOR, UnpooledByteBufAllocator.DEFAULT); final ChannelFuture channelFuture = tcpBootstrap.bind(tcpPort).addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture future) throws Exception { throttler.setServerChannel(future.channel()); } }); log.info("Binding to TCP port {}", tcpPort); return channelFuture; }
Example 5
Source File: NettyServer.java From jeesupport with MIT License | 6 votes |
public void start(){ log.debug( "--Socket Server准备中..." ) ; boss = new NioEventLoopGroup() ; work = new NioEventLoopGroup() ; port = CommonConfig.getInteger(Netty_Socket_Port); try { log.info( "Socket Server[" + port + "] 已启动." ) ; ServerBootstrap b = new ServerBootstrap() ; b.group( boss , work ) ; b.channel( NioServerSocketChannel.class ) ; b.childHandler( CommonContextHolder.getBean( NettyInitializer.class ) ) ; b.bind( port ).sync().channel().closeFuture().sync() ; } catch ( Exception e ) { String err_string = e.toString(); if( err_string.indexOf( "childHandler" ) != -1 ){ log.error( "Socket Server[" + port + "] NettyInitializer实例没有找到。" ) ; }else{ log.error( "Socket Server[" + port + "] 启动时发生错误:" + e.toString() , e ) ; } } finally { unload(); } }
Example 6
Source File: MixServer.java From incubator-hivemall with Apache License 2.0 | 6 votes |
private void acceptConnections(@Nonnull MixServerInitializer initializer, int port, @Nonnegative int numWorkers) throws InterruptedException { final EventLoopGroup bossGroup = new NioEventLoopGroup(1); final EventLoopGroup workerGroup = new NioEventLoopGroup(numWorkers); try { ServerBootstrap b = new ServerBootstrap(); b.option(ChannelOption.SO_KEEPALIVE, true); b.group(bossGroup, workerGroup); b.channel(NioServerSocketChannel.class); b.handler(new LoggingHandler(LogLevel.INFO)); b.childHandler(initializer); // Bind and start to accept incoming connections. ChannelFuture f = b.bind(port).sync(); this.state = ServerState.RUNNING; // Wait until the server socket is closed. // In this example, this does not happen, but you can do that to gracefully // shut down your server. f.channel().closeFuture().sync(); } finally { this.state = ServerState.STOPPING; workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } }
Example 7
Source File: OioEventLoopTest.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
@Test public void testTooManyServerChannels() throws Exception { EventLoopGroup g = new OioEventLoopGroup(1); ServerBootstrap b = new ServerBootstrap(); b.channel(OioServerSocketChannel.class); b.group(g); b.childHandler(new ChannelInboundHandlerAdapter()); ChannelFuture f1 = b.bind(0); f1.sync(); ChannelFuture f2 = b.bind(0); f2.await(); assertThat(f2.cause(), is(instanceOf(ChannelException.class))); assertThat(f2.cause().getMessage().toLowerCase(), containsString("too many channels")); final CountDownLatch notified = new CountDownLatch(1); f2.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { notified.countDown(); } }); notified.await(); g.shutdownGracefully(); }
Example 8
Source File: TelnetTelService.java From hasor with Apache License 2.0 | 5 votes |
@Override protected void doInitialize() { super.doInitialize(); // // .初始化常量配置 this.workerGroup = new NioEventLoopGroup(1, new NameThreadFactory("tConsole", this.classLoader)); logger.info("tConsole -> starting... at {}", this.bindAddress); // // .启动Telnet try { ServerBootstrap b = new ServerBootstrap(); b.group(this.workerGroup, this.workerGroup); b.channel(NioServerSocketChannel.class); b.handler(new LoggingHandler(LogLevel.INFO)); b.childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Unpooled.wrappedBuffer(new byte[] { '\n' }))); pipeline.addLast(new StringDecoder()); pipeline.addLast(new StringEncoder()); pipeline.addLast(nettyHandler); } }); this.telnetChannel = b.bind(this.bindAddress).sync().channel(); } catch (Throwable e) { logger.error("tConsole -> start failed, " + e.getMessage(), e); this.close(); } logger.info("tConsole -> - bindSocket at {}", this.bindAddress); }
Example 9
Source File: JT809Server.java From jt809-tcp-server with MIT License | 5 votes |
/** * 主链路(服务端)引导入口 * @throws Exception */ public void runServer() throws Exception{ //创建主线程池(接收线程池) EventLoopGroup boosGroup = new NioEventLoopGroup(serverConfig.getBossMaxThreadCount(),new DefaultThreadFactory("boosServer",true)); //创建工作线程池 EventLoopGroup workGroup = new NioEventLoopGroup(serverConfig.getWorkMaxThreadCount(),new DefaultThreadFactory("workServer",true)); try { //创建一个服务器端的程序类进行NIO的启动,同时可以设置Channel ServerBootstrap serverBootstrap = new ServerBootstrap(); //设置要使用的线程池以及当前的Channel 的类型 serverBootstrap.group(boosGroup,workGroup); serverBootstrap.channel(NioServerSocketChannel.class); serverBootstrap.handler(new LoggingHandler(LogLevel.INFO)); //接收到的信息处理器 serverBootstrap.childHandler(JT809ServerChannelInit); serverBootstrap.option(ChannelOption.SO_BACKLOG,128); serverBootstrap.option(ChannelOption.TCP_NODELAY, true); serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE,true); //ChannelFuture描述异步回调的处理操作 ChannelFuture future = serverBootstrap.bind(serverConfig.getTcpPort()).sync(); log.info("nettyServer run success,TCP-PORT:{}",serverConfig.getTcpPort()); if(businessConfig.getIsOpenClient()){ //启动从链路 this.runClient(future.channel().eventLoop()); } //等待socket被关闭 future.channel().closeFuture().sync(); } catch (Exception e){ log.error("nettyServer run fail"); e.printStackTrace(); } finally { workGroup.shutdownGracefully(); boosGroup.shutdownGracefully(); } }
Example 10
Source File: BaseChannelTest.java From netty4.0.27Learn with Apache License 2.0 | 5 votes |
ServerBootstrap getLocalServerBootstrap() { EventLoopGroup serverGroup = new LocalEventLoopGroup(); ServerBootstrap sb = new ServerBootstrap(); sb.group(serverGroup); sb.channel(LocalServerChannel.class); sb.childHandler(new ChannelInitializer<LocalChannel>() { @Override public void initChannel(LocalChannel ch) throws Exception { } }); return sb; }
Example 11
Source File: DefaultServer.java From sailfish with Apache License 2.0 | 5 votes |
public void start() throws SailfishException { ServerBootstrap boot = newServerBootstrap(); EventLoopGroup accept = NettyPlatformIndependent.newEventLoopGroup(1, new DefaultThreadFactory(RemotingConstants.SERVER_ACCEPT_THREADNAME)); if (null != config.getEventLoopGroup()) { boot.group(accept, config.getEventLoopGroup()); } else { boot.group(accept, ServerEventGroup.INSTANCE.getLoopGroup()); } final EventExecutorGroup executor = (null != config.getEventExecutorGroup() ? config.getEventExecutorGroup() : ServerEventGroup.INSTANCE.getExecutorGroup()); boot.localAddress(config.address().host(), config.address().port()); boot.childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); ch.attr(ChannelAttrKeys.OneTime.idleTimeout).set(config.idleTimeout()); ch.attr(ChannelAttrKeys.maxIdleTimeout).set(config.maxIdleTimeout()); ch.attr(ChannelAttrKeys.exchangeServer).set(DefaultServer.this); pipeline.addLast(executor, RemotingEncoder.INSTANCE, new RemotingDecoder(), new IdleStateHandler(config.idleTimeout(), 0, 0), HeartbeatChannelHandler.INSTANCE, NegotiateChannelHandler.INSTANCE, ConcreteRequestHandler.INSTANCE); } }); try { channel = boot.bind().syncUninterruptibly().channel(); } catch (Throwable cause) { throw new SailfishException(cause); } }
Example 12
Source File: DiscoveryService.java From pulsar with Apache License 2.0 | 5 votes |
/** * starts server to handle discovery-request from client-channel * * @throws Exception */ public void startServer() throws Exception { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.childOption(ChannelOption.ALLOCATOR, PulsarByteBufAllocator.DEFAULT); bootstrap.group(acceptorGroup, workerGroup); bootstrap.childOption(ChannelOption.TCP_NODELAY, true); bootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(1024, 16 * 1024, 1 * 1024 * 1024)); bootstrap.channel(EventLoopUtil.getServerSocketChannelClass(workerGroup)); EventLoopUtil.enableTriggeredMode(bootstrap); bootstrap.childHandler(new ServiceChannelInitializer(this, config, false)); // Bind and start to accept incoming connections. Preconditions.checkArgument(config.getServicePort().isPresent() || config.getServicePortTls().isPresent(), "Either ServicePort or ServicePortTls should be configured."); if (config.getServicePort().isPresent()) { // Bind and start to accept incoming connections. channelListen = bootstrap.bind(config.getServicePort().get()).sync().channel(); LOG.info("Started Pulsar Discovery service on {}", channelListen.localAddress()); } if (config.getServicePortTls().isPresent()) { ServerBootstrap tlsBootstrap = bootstrap.clone(); tlsBootstrap.childHandler(new ServiceChannelInitializer(this, config, true)); channelListenTls = tlsBootstrap.bind(config.getServicePortTls().get()).sync().channel(); LOG.info("Started Pulsar Discovery TLS service on port {}", channelListenTls.localAddress()); } this.serviceUrl = serviceUrl(); this.serviceUrlTls = serviceUrlTls(); }
Example 13
Source File: ThreadServerSocket.java From IMServer with Apache License 2.0 | 5 votes |
public void startSocket() throws InterruptedException { EventLoopGroup boss = new NioEventLoopGroup(); EventLoopGroup worker = new NioEventLoopGroup(); try { ServerBootstrap boot = new ServerBootstrap(); boot.group(boss,worker); boot.channel(NioServerSocketChannel.class); boot.childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(1024*1024,0,4,-4,0,false)); ch.pipeline().addLast(new ByteToPacketCodec()); ch.pipeline().addLast(new LoginChannelHandler(listener)); ch.pipeline().addLast(new PacketChannelHandler()); } }); boot.option(ChannelOption.SO_BACKLOG,128); boot.childOption(ChannelOption.SO_KEEPALIVE,true); channelFuture = boot.bind(port).sync(); System.out.println("服务器"+port+"开启成功..."); channelFuture.channel().closeFuture().sync(); }finally { boss.shutdownGracefully().sync(); worker.shutdownGracefully().sync(); channelFuture = null; System.out.println("服务器关闭成功..."); } }
Example 14
Source File: HttpServer.java From ServerCore with Apache License 2.0 | 5 votes |
public void createNetWork() { bossGroup = new NioEventLoopGroup(bossThreadCount); workerGroup = new NioEventLoopGroup(workThreadCount); bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup); bootstrap.channel(NioServerSocketChannel.class); bootstrap.option(ChannelOption.SO_BACKLOG, 1024); bootstrap.childOption(ChannelOption.TCP_NODELAY, true); bootstrap.childOption(ChannelOption.SO_RCVBUF, 128 * 1024); bootstrap.childOption(ChannelOption.SO_SNDBUF, 128 * 1024); bootstrap.handler(new LoggingHandler(LogLevel.DEBUG)); bootstrap.childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { ChannelPipeline pip = ch.pipeline(); pip.addLast("codec", new HttpServerCodec()); pip.addLast("aggregator", new HttpObjectAggregator(512 * 1024)); pip.addLast("responseEncoder", new ResponseEncoder()); pip.addLast("requestDecoder", new RequestDecoder()); pip.addLast("requestHandler", new HttpHandler()); } }); }
Example 15
Source File: WsServer.java From wind-im with Apache License 2.0 | 5 votes |
public WsServer() { executor = new SimpleExecutor<Command, CommandResponse>(); loadExecutor(executor); // 负责对外连接线程 parentGroup = new NioEventLoopGroup(); // 负责对内分发业务的线程 childGroup = new NioEventLoopGroup(); bootstrap = new ServerBootstrap(); bootstrap.group(parentGroup, childGroup); bootstrap.channel(NioServerSocketChannel.class); bootstrap.childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { // 30秒空闲时间设置 ch.pipeline().addLast(new IdleStateHandler(30, 0, 60)); // HttpServerCodec:将请求和应答消息解码为HTTP消息 ch.pipeline().addLast(new HttpServerCodec()); // 针对大文件上传时,把 HttpMessage 和 HttpContent 聚合成一个 // FullHttpRequest,并定义可以接受的数据大小64M(可以支持params+multipart) ch.pipeline().addLast(new HttpObjectAggregator(64 * 1024)); // 针对大文件下发,分块写数据 ch.pipeline().addLast(new ChunkedWriteHandler()); // WebSocket 访问地址 // ch.pipeline().addLast(new WebSocketServerProtocolHandler("/akaxin/ws")); // 自定义handler ch.pipeline().addLast(new WsServerHandler(executor)); } }); }
Example 16
Source File: MgsServer.java From push with Apache License 2.0 | 5 votes |
@Override public void run() { ServerBootstrap b = new ServerBootstrap();// 引导辅助程序 bossGroup = new NioEventLoopGroup(BIZGROUPSIZE); workerGroup = new NioEventLoopGroup(BIZTHREADSIZE); try { b.group(bossGroup, workerGroup); b.channel(NioServerSocketChannel.class);// 设置nio类型的channel b.childHandler(new ChannelInitializer<SocketChannel>() {// 有连接到达时会创建一个channel protected void initChannel(SocketChannel ch) throws Exception { logger.debug("客户端:{} 初始化", ch.remoteAddress()); // pipeline管理channel中的Handler,在channel队列中添加一个handler来处理业务 ch.pipeline().addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4)); ch.pipeline().addLast("frameEncoder", new LengthFieldPrepender(4)); ch.pipeline().addLast("decoder", msgPackDecode); ch.pipeline().addLast("encoder", msgPackEncode); ch.pipeline().addLast(serverHandler); } }); b.option(ChannelOption.SO_BACKLOG, 128); b.childOption(ChannelOption.SO_KEEPALIVE, true); logger.info("server start : {}", port); status = "run"; ChannelFuture f = b.bind(port).sync();// 配置完成,开始绑定server,通过调用sync同步方法阻塞直到绑定成功 channel = f.channel(); f.channel().closeFuture().sync();// 应用程序会一直等待,直到channel关闭 } catch (Exception e) { status = "error"; e.printStackTrace(); } }
Example 17
Source File: Server.java From dubbo-2.6.5 with Apache License 2.0 | 5 votes |
/** * start server, bind port */ public void start() throws Throwable { if (!hasStarted.compareAndSet(false, true)) { return; } boss = new NioEventLoopGroup(0, new DefaultThreadFactory("qos-boss", true)); worker = new NioEventLoopGroup(0, new DefaultThreadFactory("qos-worker", true)); ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(boss, worker); serverBootstrap.channel(NioServerSocketChannel.class); serverBootstrap.childOption(ChannelOption.TCP_NODELAY, true); serverBootstrap.childOption(ChannelOption.SO_REUSEADDR, true); serverBootstrap.childHandler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { ch.pipeline().addLast(new QosProcessHandler(welcome, acceptForeignIp)); } }); try { serverBootstrap.bind(port).sync(); logger.info("qos-server bind localhost:" + port); } catch (Throwable throwable) { logger.error("qos-server can not bind localhost:" + port, throwable); throw throwable; } }
Example 18
Source File: PCEPDispatcherImpl.java From bgpcep with Eclipse Public License 1.0 | 5 votes |
synchronized ServerBootstrap createServerBootstrap(final ChannelPipelineInitializer initializer) { final ServerBootstrap b = new ServerBootstrap(); b.childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(final SocketChannel ch) { initializer.initializeChannel(ch, new DefaultPromise<>(PCEPDispatcherImpl.this.executor)); } }); b.option(ChannelOption.SO_BACKLOG, SOCKET_BACKLOG_SIZE); b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); if (Epoll.isAvailable()) { b.channel(EpollServerSocketChannel.class); b.childOption(EpollChannelOption.EPOLL_MODE, EpollMode.LEVEL_TRIGGERED); } else { b.channel(NioServerSocketChannel.class); } if (!this.keys.isEmpty()) { if (Epoll.isAvailable()) { b.option(EpollChannelOption.TCP_MD5SIG, this.keys); } else { throw new UnsupportedOperationException(Epoll.unavailabilityCause().getCause()); } } // Make sure we are doing round-robin processing b.childOption(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(1)); if (b.config().group() == null) { b.group(this.bossGroup, this.workerGroup); } return b; }
Example 19
Source File: NettyHttpServer.java From netty-http-server with Apache License 2.0 | 4 votes |
@Override public void onApplicationEvent(@NonNull ApplicationStartedEvent event) { ServerBootstrap bootstrap = new ServerBootstrap(); EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); bootstrap.group(bossGroup, workerGroup); bootstrap.channel(NioServerSocketChannel.class); bootstrap.childOption(NioChannelOption.TCP_NODELAY, true); bootstrap.childOption(NioChannelOption.SO_REUSEADDR,true); bootstrap.childOption(NioChannelOption.SO_KEEPALIVE,false); bootstrap.childOption(NioChannelOption.SO_RCVBUF, 2048); bootstrap.childOption(NioChannelOption.SO_SNDBUF, 2048); bootstrap.childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) { ch.pipeline().addLast("codec", new HttpServerCodec()); ch.pipeline().addLast("aggregator", new HttpObjectAggregator(512 * 1024)); ch.pipeline().addLast("logging", new FilterLogginglHandler()); ch.pipeline().addLast("interceptor", interceptorHandler); ch.pipeline().addLast("bizHandler", httpServerHandler); } }) ; ChannelFuture channelFuture = bootstrap.bind(port).syncUninterruptibly().addListener(future -> { String logBanner = "\n\n" + "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n" + "* *\n" + "* *\n" + "* Netty Http Server started on port {}. *\n" + "* *\n" + "* *\n" + "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n"; LOGGER.info(logBanner, port); }); channelFuture.channel().closeFuture().addListener(future -> { LOGGER.info("Netty Http Server Start Shutdown ............"); bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); }); }
Example 20
Source File: HttpServer.java From wind-im with Apache License 2.0 | 4 votes |
public HttpServer() { try { executor = new SimpleExecutor<Command, CommandResponse>(); loadExecutor(executor); int needThreadNum = Runtime.getRuntime().availableProcessors() + 1; int parentNum = 5;// accept from channel socket int childNum = needThreadNum * 2 + 5;// give to business handler bootstrap = new ServerBootstrap(); parentGroup = new NioEventLoopGroup(parentNum); childGroup = new NioEventLoopGroup(childNum); bootstrap.group(parentGroup, childGroup); bootstrap.channel(NioServerSocketChannel.class); // 接受连接的可连接队列大小 bootstrap.option(ChannelOption.SO_BACKLOG, 120); bootstrap.option(ChannelOption.SO_REUSEADDR, true); // 设置缓存大小 bootstrap.option(ChannelOption.SO_RCVBUF, 256 * 1024); bootstrap.option(ChannelOption.SO_SNDBUF, 256 * 1024);// 256 KB/字节 bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true); bootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); /** * 接受缓存区,动态内存分配端的算法 */ bootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, AdaptiveRecvByteBufAllocator.DEFAULT); bootstrap.childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new HttpResponseEncoder()); ch.pipeline().addLast(new HttpRequestDecoder()); ch.pipeline().addLast("aggregator", new HttpObjectAggregator(65536)); ch.pipeline().addLast("streamer", new ChunkedWriteHandler()); ch.pipeline().addLast(new HttpServerHandler(executor)); } }); } catch (Exception e) { closeGracefylly(); logger.error(AkxProject.PLN + " init http server error.", e); System.exit(-200); } }