Java Code Examples for io.netty.bootstrap.ServerBootstrap#channel()
The following examples show how to use
io.netty.bootstrap.ServerBootstrap#channel() .
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: H2PriorKnowledgeFeatureParityTest.java From servicetalk with Apache License 2.0 | 6 votes |
private InetSocketAddress bindH2Server(ChannelHandler childChannelHandler, Consumer<ChannelPipeline> parentChannelInitializer) { ServerBootstrap sb = new ServerBootstrap(); sb.group(serverEventLoopGroup); sb.channel(serverChannel(serverEventLoopGroup, InetSocketAddress.class)); sb.childHandler(new ChannelInitializer<Channel>() { @Override protected void initChannel(final Channel ch) { ch.pipeline().addLast( Http2FrameCodecBuilder.forServer().build(), new Http2MultiplexHandler(childChannelHandler)); parentChannelInitializer.accept(ch.pipeline()); } }); serverAcceptorChannel = sb.bind(localAddress(0)).syncUninterruptibly().channel(); return (InetSocketAddress) serverAcceptorChannel.localAddress(); }
Example 2
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 3
Source File: TcpProtocolServer.java From Okra with Apache License 2.0 | 6 votes |
@Override public ServerBootstrap createBootstrap() { bootstrap = new ServerBootstrap(); if (isEpollAvailable) { this.parentGroup = new EpollEventLoopGroup(); this.childGroup = new EpollEventLoopGroup(); bootstrap.channel(EpollServerSocketChannel.class); } else { this.parentGroup = new NioEventLoopGroup(); this.childGroup = new NioEventLoopGroup(); bootstrap.channel(NioServerSocketChannel.class); } bootstrap.group(parentGroup(), childGroup()); bootstrap.childHandler(newChannelInitializer()); bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); // bootstrap.option(ChannelOption.SO_REUSEADDR, true); // bootstrap.childOption(ChannelOption.TCP_NODELAY, true); bootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); return bootstrap; }
Example 4
Source File: MockBrokerService.java From pulsar with Apache License 2.0 | 6 votes |
public void startMockBrokerService() throws Exception { ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("mock-pulsar-%s").build(); final int numThreads = 2; final int MaxMessageSize = 5 * 1024 * 1024; try { workerGroup = EventLoopUtil.newEventLoopGroup(numThreads, threadFactory); ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(workerGroup, workerGroup); bootstrap.channel(EventLoopUtil.getServerSocketChannelClass(workerGroup)); bootstrap.childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast("frameDecoder", new LengthFieldBasedFrameDecoder(MaxMessageSize, 0, 4, 0, 4)); ch.pipeline().addLast("handler", new MockServerCnx()); } }); // Bind and start to accept incoming connections. listenChannel = bootstrap.bind(0).sync().channel(); } catch (Exception e) { throw e; } }
Example 5
Source File: DefaultServer.java From sailfish with Apache License 2.0 | 6 votes |
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; }
Example 6
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 7
Source File: EpollReuseAddrTest.java From netty4.0.27Learn with Apache License 2.0 | 5 votes |
private static ServerBootstrap createServerBootstrap() { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(EpollSocketTestPermutation.EPOLL_BOSS_GROUP, EpollSocketTestPermutation.EPOLL_WORKER_GROUP); bootstrap.channel(EpollServerSocketChannel.class); bootstrap.childHandler(new DummyHandler()); InetSocketAddress address = new InetSocketAddress(NetUtil.LOCALHOST, TestUtils.getFreePort()); bootstrap.localAddress(address); return bootstrap; }
Example 8
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 9
Source File: PeerServer.java From gsc-core with GNU Lesser General Public License v3.0 | 5 votes |
public void start(int port) { EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(args.getTcpNettyWorkThreadNum()); GSCChannelInitializer GSCChannelInitializer = ctx.getBean(GSCChannelInitializer.class, ""); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup); b.channel(NioServerSocketChannel.class); b.option(ChannelOption.SO_KEEPALIVE, true); b.option(ChannelOption.MESSAGE_SIZE_ESTIMATOR, DefaultMessageSizeEstimator.DEFAULT); b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, this.args.getNodeConnectionTimeout()); b.handler(new LoggingHandler()); b.childHandler(GSCChannelInitializer); // Start the client. logger.info("TCP listener started, bind port {}", port); channelFuture = b.bind(port).sync(); listening = true; // Wait until the connection is closed. channelFuture.channel().closeFuture().sync(); logger.info("TCP listener is closed"); } catch (Exception e) { logger.error("Start TCP server failed.", e); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); listening = false; } }
Example 10
Source File: HttpUploadServer.java From netty4.0.27Learn with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) { SelfSignedCertificate ssc = new SelfSignedCertificate(); sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey()); } else { sslCtx = null; } EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup); b.channel(NioServerSocketChannel.class); b.handler(new LoggingHandler(LogLevel.INFO)); b.childHandler(new HttpUploadServerInitializer(sslCtx)); Channel ch = b.bind(PORT).sync().channel(); System.err.println("Open your web browser and navigate to " + (SSL? "https" : "http") + "://127.0.0.1:" + PORT + '/'); ch.closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
Example 11
Source File: OioEventLoopTest.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
@Test public void testTooManyClientChannels() throws Exception { EventLoopGroup g = new OioEventLoopGroup(1); ServerBootstrap sb = new ServerBootstrap(); sb.channel(OioServerSocketChannel.class); sb.group(g); sb.childHandler(new ChannelInboundHandlerAdapter()); ChannelFuture f1 = sb.bind(0); f1.sync(); Bootstrap cb = new Bootstrap(); cb.channel(OioSocketChannel.class); cb.group(g); cb.handler(new ChannelInboundHandlerAdapter()); ChannelFuture f2 = cb.connect(NetUtil.LOCALHOST, ((InetSocketAddress) f1.channel().localAddress()).getPort()); 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 12
Source File: DefaultChannelGroupTest.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
@Test public void testNotThrowBlockingOperationException() throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); final ChannelGroup allChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup); b.childHandler(new ChannelInboundHandlerAdapter() { @Override public void channelActive(ChannelHandlerContext ctx) { allChannels.add(ctx.channel()); } }); b.channel(NioServerSocketChannel.class); ChannelFuture f = b.bind(0).syncUninterruptibly(); if (f.isSuccess()) { allChannels.add(f.channel()); allChannels.close().awaitUninterruptibly(); } bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); bossGroup.terminationFuture().sync(); workerGroup.terminationFuture().sync(); }
Example 13
Source File: NettyRestServer.java From turbo-rpc with Apache License 2.0 | 5 votes |
public void start() throws InterruptedException { InetSocketAddress inet = new InetSocketAddress(hostPort.host, hostPort.port); ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(eventLoopGroup); bootstrap.option(ChannelOption.SO_BACKLOG, 1024); bootstrap.option(ChannelOption.SO_REUSEADDR, true); bootstrap.option(ChannelOption.SO_RCVBUF, 256 * 1024); if (eventLoopGroup instanceof EpollEventLoopGroup) { bootstrap.option(EpollChannelOption.SO_REUSEPORT, true); bootstrap.channel(EpollServerSocketChannel.class); } else if (eventLoopGroup instanceof NioEventLoopGroup) { bootstrap.channel(NioServerSocketChannel.class); } bootstrap.childHandler(new NettyRestChannelInitializer(invokerFactory, jsonMapper, filters)); bootstrap.childOption(ChannelOption.SO_REUSEADDR, true); bootstrap.childOption(ChannelOption.SO_RCVBUF, 256 * 1024); bootstrap.childOption(ChannelOption.SO_SNDBUF, 256 * 1024); bootstrap.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK, // new WriteBufferWaterMark(1024 * 1024, 2048 * 1024)); channel = bootstrap.bind(inet).sync().channel(); System.out.println("NettyRestServer started. Listening on: " + hostPort); }
Example 14
Source File: HttpUploadServer.java From tools-journey with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) { SelfSignedCertificate ssc = new SelfSignedCertificate(); sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build(); } else { sslCtx = null; } EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup); b.channel(NioServerSocketChannel.class); b.handler(new LoggingHandler(LogLevel.INFO)); b.childHandler(new HttpUploadServerInitializer(sslCtx)); Channel ch = b.bind(PORT).sync().channel(); System.err.println("Open your web browser and navigate to " + (SSL? "https" : "http") + "://127.0.0.1:" + PORT + '/'); ch.closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
Example 15
Source File: WsServer.java From openzaly 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: NettyServer.java From openzaly with Apache License 2.0 | 4 votes |
public NettyServer() { try { bootstrap = new ServerBootstrap(); int needThreadNum = Runtime.getRuntime().availableProcessors() + 1; int parentNum = 10;// accept from channel socket int childNum = needThreadNum * 5 + 10;// give to business handler // 处理服务端事件组 parentGroup = new NioEventLoopGroup(parentNum, new PrefixThreadFactory("bim-boss-evenloopgroup")); // 处理客户端连接请求的事件组 childGroup = new NioEventLoopGroup(childNum, new PrefixThreadFactory("bim-worker-evenloopgroup")); // 用户处理所有的channel bootstrap.group(parentGroup, childGroup); bootstrap.channel(NioServerSocketChannel.class); /** * 对应的是tcp/ip协议listen函数中的backlog参数,函数listen(int socketfd,int * backlog)用来初始化服务端可连接队列. 服务端处理客户端连接请求是顺序处理的,所以同一时间只能处理一个客户端连接,多个客户端来的时候, * 服务端将不能处理的客户端连接请求放在队列中等待处理,backlog参数指定了队列的大小 */ bootstrap.option(ChannelOption.SO_BACKLOG, 2000); /** * 允许监听的端口共存 */ bootstrap.option(ChannelOption.SO_REUSEADDR, true); /** * ChannelOption.SO_SNDBUF参数对应于套接字选项中的SO_SNDBUF, * ChannelOption.SO_RCVBUF参数对应于套接字选项中的SO_RCVBUF这两个参数 * 用于操作接收缓冲区和发送缓冲区的大小,接收缓冲区用于保存网络协议站内收到的数据, 直到应用程序读取成功,发送缓冲区用于保存发送数据,直到发送成 */ bootstrap.option(ChannelOption.SO_RCVBUF, 256 * 1024); bootstrap.option(ChannelOption.SO_SNDBUF, 256 * 1024);// 256 KB/字节 /** * 在4.x版本中,UnpooledByteBufAllocator是默认的allocator,尽管其存在某些限制。 * 现在PooledByteBufAllocator已经广泛使用一段时间,并且我们有了增强的缓冲区泄漏追踪机制, * 所以是时候让PooledByteBufAllocator成为默认了。<br> * 总结:Netty4使用对象池,重用缓冲区 */ bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); /** * 当设置该选项以后,如果在两小时内没有数据的通信时,TCP会自动发送一个活动探测数据报文。 */ bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true); /** * Nagle算法是将小的数据包组装为更大的帧然后进行发送,而不是输入一次发送一次, 因此在数据包不足的时候会等待其他数据的到了,组装成大的数据包进行发送, * 虽然该方式有效提高网络的有效负载, 但是却造成了延时, * 而该参数的作用就是禁止使用Nagle算法,使用于小数据即时传输,于TCP_NODELAY相对应的是TCP_CORK, * 该选项是需要等到发送的数据量最大的时候,一次性发送 */ bootstrap.childOption(ChannelOption.TCP_NODELAY, true); bootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); /** * 接受缓存区,动态内存分配端的算法 */ bootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, AdaptiveRecvByteBufAllocator.DEFAULT); // the ChannelHandler to use for serving the requests. bootstrap.handler(new LoggingHandler(LogLevel.DEBUG)); // Set the ChannelHandler which is used to serve the request for the // Channel's bootstrap.childHandler(new NettyChannelInitializer()); executor = new SimpleExecutor<Command, CommandResponse>(); loadExecutor(executor); } catch (Exception e) { closeGracefully(); logger.error(AkxProject.PLN + " init openzaly netty-server error.", e); System.exit(-10); } }
Example 18
Source File: NettyServerDemo.java From NettyChat with Apache License 2.0 | 4 votes |
public static void main(String[] args) { //boss线程监听端口,worker线程负责数据读写 EventLoopGroup boss = new NioEventLoopGroup(); EventLoopGroup worker = new NioEventLoopGroup(); try { //辅助启动类 ServerBootstrap bootstrap = new ServerBootstrap(); //设置线程池 bootstrap.group(boss, worker); //设置socket工厂 bootstrap.channel(NioServerSocketChannel.class); //设置管道工厂 bootstrap.childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { //获取管道 ChannelPipeline pipeline = socketChannel.pipeline(); pipeline.addLast("frameEncoder", new LengthFieldPrepender(2)); pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(65535, 0, 2, 0, 2)); pipeline.addLast(new ProtobufDecoder(MessageProtobuf.Msg.getDefaultInstance())); pipeline.addLast(new ProtobufEncoder()); //处理类 pipeline.addLast(new ServerHandler()); } }); //设置TCP参数 //1.链接缓冲池的大小(ServerSocketChannel的设置) bootstrap.option(ChannelOption.SO_BACKLOG, 1024); //维持链接的活跃,清除死链接(SocketChannel的设置) bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true); //关闭延迟发送 bootstrap.childOption(ChannelOption.TCP_NODELAY, true); //绑定端口 ChannelFuture future = bootstrap.bind(8855).sync(); System.out.println("server start ...... "); //等待服务端监听端口关闭 future.channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); } finally { //优雅退出,释放线程池资源 boss.shutdownGracefully(); worker.shutdownGracefully(); } }
Example 19
Source File: HttpServer.java From openzaly 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); } }
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); } }