Java Code Examples for io.netty.bootstrap.ServerBootstrap#childOption()
The following examples show how to use
io.netty.bootstrap.ServerBootstrap#childOption() .
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: HttpHelloWorldServer.java From netty-learning-example with Apache License 2.0 | 6 votes |
public static void main(String[] args) throws Exception { // Configure the server. EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.option(ChannelOption.SO_BACKLOG, 1024); b.childOption(ChannelOption.TCP_NODELAY,true); b.childOption(ChannelOption.SO_KEEPALIVE,true); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new HttpHelloWorldServerInitializer()); Channel ch = b.bind(PORT).sync().channel(); logger.info("Netty http server listening on port "+ PORT); ch.closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
Example 2
Source File: HelloWebServer.java From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License | 6 votes |
private void doRun(EventLoopGroup loupGroup, Class<? extends ServerChannel> serverChannelClass, IoMultiplexer multiplexer) throws InterruptedException { try { InetSocketAddress inet = new InetSocketAddress(port); ServerBootstrap b = new ServerBootstrap(); if (multiplexer == IoMultiplexer.EPOLL) { b.option(EpollChannelOption.SO_REUSEPORT, true); } b.option(ChannelOption.SO_BACKLOG, 8192); b.option(ChannelOption.SO_REUSEADDR, true); b.group(loupGroup).channel(serverChannelClass).childHandler(new HelloServerInitializer(loupGroup.next())); b.childOption(ChannelOption.SO_REUSEADDR, true); Channel ch = b.bind(inet).sync().channel(); System.out.printf("Httpd started. Listening on: %s%n", inet.toString()); ch.closeFuture().sync(); } finally { loupGroup.shutdownGracefully().sync(); } }
Example 3
Source File: NettyTcpServer.java From spring-boot-protocol with Apache License 2.0 | 6 votes |
@Override protected void config(ServerBootstrap bootstrap) throws Exception{ super.config(bootstrap); if(SystemPropertyUtil.get("io.netty.leakDetectionLevel") == null && SystemPropertyUtil.get("io.netty.leakDetection.level") == null){ ResourceLeakDetector.setLevel(properties.getResourceLeakDetectorLevel()); } if(SystemPropertyUtil.get("io.netty.maxDirectMemory") == null){ long maxDirectMemory = -1; System.setProperty("io.netty.maxDirectMemory", String.valueOf(maxDirectMemory)); } bootstrap.childOption(ChannelOption.WRITE_SPIN_COUNT,Integer.MAX_VALUE); bootstrap.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(32 * 1024,Integer.MAX_VALUE)); bootstrap.childOption(ChannelOption.AUTO_CLOSE,true); bootstrap.childOption(ChannelOption.TCP_NODELAY, properties.isTcpNodelay()); for (ServerListener serverListener : serverListeners) { serverListener.config(bootstrap); } }
Example 4
Source File: NetworkServiceImpl.java From ServerCore with Apache License 2.0 | 5 votes |
NetworkServiceImpl(final NetworkServiceBuilder builder) { int bossLoopGroupCount = builder.getBossLoopGroupCount(); int workerLoopGroupCount = builder.getWorkerLoopGroupCount(); this.port = builder.getPort(); final SslContext sslCtx; bossGroup = new NioEventLoopGroup(bossLoopGroupCount); workerGroup = new NioEventLoopGroup(workerLoopGroupCount); if (builder.isSsl()) { try { File keyCertChainFile = new File(builder.getSslKeyCertChainFile()); File keyFile = new File(builder.getSslKeyFile()); sslCtx = SslContext.newServerContext(keyCertChainFile, keyFile); } catch (Exception var4) { throw new RuntimeException("sslCtx create failed.", var4); } } else { sslCtx = null; } 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)); if (builder.isWebSocket()) { bootstrap.childHandler(new WebSocketHandler(builder, sslCtx)); } else { bootstrap.childHandler(new SocketHandler(builder)); } }
Example 5
Source File: BrokerService.java From pulsar with Apache License 2.0 | 5 votes |
private ServerBootstrap defaultServerBootstrap() { 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); return bootstrap; }
Example 6
Source File: NettyServer.java From dubbo3 with Apache License 2.0 | 5 votes |
@Override protected void doOpen() throws Throwable { NettyHelper.setNettyLoggerFactory(); ServerBootstrap bootstrap = new ServerBootstrap(); final NettyHandler nettyHandler = new NettyHandler(getUrl(), this); channels = nettyHandler.getChannels(); bossGroup = new NioEventLoopGroup(1, (new NamedThreadFactory("NettyServerBoss", true))); workerGroup = new NioEventLoopGroup(getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS), new NamedThreadFactory("NettyServerWorker", true)); bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class); bootstrap.childOption(ChannelOption.TCP_NODELAY, false); bootstrap.childHandler(new ChannelInitializer() { public void initChannel(io.netty.channel.Channel ch) { NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyServer.this); ChannelPipeline channelPipeline = ch.pipeline(); channelPipeline.addLast("decoder", adapter.getDecoder()); channelPipeline.addLast("encoder", adapter.getEncoder()); channelPipeline.addLast("handler", nettyHandler); } }); // bind ChannelFuture channelFuture = bootstrap.bind(getBindAddress()); channelFuture.awaitUninterruptibly(); channel = channelFuture.channel(); }
Example 7
Source File: DoradoServer.java From dorado with Apache License 2.0 | 5 votes |
public void start() { // print dorado ascii-art logo,use figlet generate ascii-art logo if (!Dorado.springInitialized) { System.out.println(ClassLoaderUtils.getResoureAsString("dorado-ascii")); System.out.println(); } if (builder.isSpringOn() && !Dorado.springInitialized) { SpringContainer.create(builder.scanPackages()); } Webapp.create(builder.scanPackages(), builder.isSpringOn()); EventLoopGroup acceptor = new NioEventLoopGroup(builder.getAcceptors()); EventLoopGroup worker = new NioEventLoopGroup(builder.getIoWorkers()); ServerBootstrap bootstrap = null; try { bootstrap = new ServerBootstrap().group(acceptor, worker).channel(NioServerSocketChannel.class) .childHandler(new DoradoChannelInitializer(builder)); bootstrap.option(ChannelOption.SO_BACKLOG, builder.getBacklog()); bootstrap.childOption(ChannelOption.TCP_NODELAY, true); bootstrap.childOption(ChannelOption.SO_SNDBUF, builder.getSendBuffer()); bootstrap.childOption(ChannelOption.SO_RCVBUF, builder.getRecvBuffer()); ChannelFuture f = bootstrap.bind(builder.getPort()).sync(); LogUtils.info(String.format("Dorado application initialized with port: %d (http)", builder.getPort())); f.channel().closeFuture().sync(); } catch (Throwable ex) { LogUtils.error("Start dorado application failed, cause: " + ex.getMessage(), ex); } finally { worker.shutdownGracefully(); acceptor.shutdownGracefully(); } }
Example 8
Source File: IpcdServer.java From arcusipcd with Apache License 2.0 | 5 votes |
@SuppressWarnings( {"rawtypes", "unchecked"} ) public void startServer() throws Exception { try { serverBootstrap = new ServerBootstrap(); serverBootstrap.group(bossGroup, workerGroup); serverBootstrap.channel(NioServerSocketChannel.class); for (Map.Entry<ChannelOption, Object> e : channelOptions.entrySet()) { serverBootstrap.childOption(e.getKey(), e.getValue()); } serverBootstrap.childHandler(channelInitializer); Channel ch = serverBootstrap.bind(portNumber).sync().channel(); // TODO log msg server start if (debugConsole) { BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in)); Console console = new Console(); while (true) { String msg = consoleReader.readLine(); if (msg == null) { break; } console.handleInput(msg); } } else { ch.closeFuture().sync(); } } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
Example 9
Source File: NettyRemotingServer.java From DDMQ with Apache License 2.0 | 4 votes |
@Override public void start() { this.defaultEventExecutorGroup = new DefaultEventExecutorGroup( nettyServerConfig.getServerWorkerThreads(), new ThreadFactory() { private AtomicInteger threadIndex = new AtomicInteger(0); @Override public Thread newThread(Runnable r) { return new Thread(r, "NettyServerCodecThread_" + this.threadIndex.incrementAndGet()); } }); ServerBootstrap childHandler = this.serverBootstrap.group(this.eventLoopGroupBoss, this.eventLoopGroupSelector) .channel(useEpoll() ? EpollServerSocketChannel.class : NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 1024) .option(ChannelOption.SO_REUSEADDR, true) .option(ChannelOption.SO_KEEPALIVE, false) .childOption(ChannelOption.TCP_NODELAY, true) .childOption(ChannelOption.SO_SNDBUF, nettyServerConfig.getServerSocketSndBufSize()) .childOption(ChannelOption.SO_RCVBUF, nettyServerConfig.getServerSocketRcvBufSize()) .localAddress(new InetSocketAddress(this.nettyServerConfig.getListenPort())) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline() .addLast(defaultEventExecutorGroup, HANDSHAKE_HANDLER_NAME, new HandshakeHandler(TlsSystemConfig.tlsMode)) .addLast(defaultEventExecutorGroup, new NettyEncoder(), new NettyDecoder(), new IdleStateHandler(0, 0, nettyServerConfig.getServerChannelMaxIdleTimeSeconds()), new NettyConnectManageHandler(), new NettyServerHandler() ); } }); if (nettyServerConfig.isServerPooledByteBufAllocatorEnable()) { childHandler.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); } try { ChannelFuture sync = this.serverBootstrap.bind().sync(); InetSocketAddress addr = (InetSocketAddress) sync.channel().localAddress(); this.port = addr.getPort(); } catch (InterruptedException e1) { throw new RuntimeException("this.serverBootstrap.bind().sync() InterruptedException", e1); } if (this.channelEventListener != null) { this.nettyEventExecutor.start(); } this.timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { try { NettyRemotingServer.this.scanResponseTable(); } catch (Throwable e) { log.error("scanResponseTable exception", e); } } }, 1000 * 3, 1000); }
Example 10
Source File: Netty4Transport.java From crate with Apache License 2.0 | 4 votes |
private void createServerBootstrap(ProfileSettings profileSettings) { String name = profileSettings.profileName; if (logger.isDebugEnabled()) { logger.debug("using profile[{}], worker_count[{}], port[{}], bind_host[{}], publish_host[{}], compress[{}], " + "receive_predictor[{}->{}]", name, workerCount, profileSettings.portOrRange, profileSettings.bindHosts, profileSettings.publishHosts, compress, receivePredictorMin, receivePredictorMax); } final ThreadFactory workerFactory = daemonThreadFactory(this.settings, TRANSPORT_SERVER_WORKER_THREAD_NAME_PREFIX, name); final ServerBootstrap serverBootstrap = new ServerBootstrap(); if (Epoll.isAvailable()) { serverBootstrap.group(new EpollEventLoopGroup(workerCount, workerFactory)); serverBootstrap.channel(EpollServerSocketChannel.class); } else { serverBootstrap.group(new NioEventLoopGroup(workerCount, workerFactory)); serverBootstrap.channel(NioServerSocketChannel.class); } serverBootstrap.childHandler(new ServerChannelInitializer(name)); serverBootstrap.childOption(ChannelOption.TCP_NODELAY, profileSettings.tcpNoDelay); serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, profileSettings.tcpKeepAlive); if (profileSettings.sendBufferSize.getBytes() != -1) { serverBootstrap.childOption(ChannelOption.SO_SNDBUF, Math.toIntExact(profileSettings.sendBufferSize.getBytes())); } if (profileSettings.receiveBufferSize.getBytes() != -1) { serverBootstrap.childOption(ChannelOption.SO_RCVBUF, Math.toIntExact(profileSettings.receiveBufferSize.bytesAsInt())); } serverBootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, recvByteBufAllocator); serverBootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, recvByteBufAllocator); serverBootstrap.option(ChannelOption.SO_REUSEADDR, profileSettings.reuseAddress); serverBootstrap.childOption(ChannelOption.SO_REUSEADDR, profileSettings.reuseAddress); serverBootstrap.validate(); serverBootstraps.put(name, serverBootstrap); }
Example 11
Source File: NettyRemotingServer.java From rocketmq-all-4.1.0-incubating with Apache License 2.0 | 4 votes |
@Override public void start() { this.defaultEventExecutorGroup = new DefaultEventExecutorGroup( nettyServerConfig.getServerWorkerThreads(), new ThreadFactory() { private AtomicInteger threadIndex = new AtomicInteger(0); @Override public Thread newThread(Runnable r) { return new Thread(r, "NettyServerCodecThread_" + this.threadIndex.incrementAndGet()); } }); //netty 服务端 ServerBootstrap childHandler = this.serverBootstrap.group(this.eventLoopGroupBoss, this.eventLoopGroupSelector) //这里指定EpollServerSocketChannel或者NioServerSocketChannel类初始化channel用来接受客户端请求。 .channel(useEpoll() ? EpollServerSocketChannel.class : NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 1024) .option(ChannelOption.SO_REUSEADDR, true) .option(ChannelOption.SO_KEEPALIVE, false) .childOption(ChannelOption.TCP_NODELAY, true) .childOption(ChannelOption.SO_SNDBUF, nettyServerConfig.getServerSocketSndBufSize()) .childOption(ChannelOption.SO_RCVBUF, nettyServerConfig.getServerSocketRcvBufSize()) .localAddress(new InetSocketAddress(this.nettyServerConfig.getListenPort())) //比如namesrv前面有设置nettyServerConfig.setListenPort(9876)类似操作 //通常会为新SocketChannel通过添加一些handler,来设置ChannelPipeline。ChannelInitializer 是一个特殊的handler,其中initChannel方法可以为SocketChannel 的pipeline添加指定handler。 .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast( defaultEventExecutorGroup, new NettyEncoder(), //编码 new NettyDecoder(), //解码 new IdleStateHandler(0, 0, nettyServerConfig.getServerChannelMaxIdleTimeSeconds()), //心跳检查 new NettyConnectManageHandler(), new NettyServerHandler()); } }); if (nettyServerConfig.isServerPooledByteBufAllocatorEnable()) { // Netty4使用对象池,重用缓冲区 childHandler.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); } try { ChannelFuture sync = this.serverBootstrap.bind().sync();//通过绑定,就可以对外提供服务了。 InetSocketAddress addr = (InetSocketAddress) sync.channel().localAddress(); this.port = addr.getPort(); } catch (InterruptedException e1) { throw new RuntimeException("this.serverBootstrap.bind().sync() InterruptedException", e1); } if (this.channelEventListener != null) { this.nettyEventExecutor.start(); } // 每隔1秒扫描下异步调用超时情况 this.timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { try { NettyRemotingServer.this.scanResponseTable(); } catch (Exception e) { log.error("scanResponseTable exception", e); } } }, 1000 * 3, 1000); }
Example 12
Source File: NettyRemotingServer.java From jmqtt with Apache License 2.0 | 4 votes |
private void startWebsocketServer(boolean useSsl, Integer port){ ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(selectorGroup,ioGroup) .channel(clazz) .option(ChannelOption.SO_BACKLOG, nettyConfig.getTcpBackLog()) .childOption(ChannelOption.TCP_NODELAY, nettyConfig.isTcpNoDelay()) .childOption(ChannelOption.SO_SNDBUF, nettyConfig.getTcpSndBuf()) .option(ChannelOption.SO_RCVBUF, nettyConfig.getTcpRcvBuf()) .option(ChannelOption.SO_REUSEADDR, nettyConfig.isTcpReuseAddr()) .childOption(ChannelOption.SO_KEEPALIVE, nettyConfig.isTcpKeepAlive()) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { ChannelPipeline pipeline = socketChannel.pipeline(); if (useSsl) { pipeline.addLast("ssl", NettySslHandler.getSslHandler( socketChannel, nettyConfig.isUseClientCA(), nettyConfig.getSslKeyStoreType(), brokerConfig.getJmqttHome() + nettyConfig.getSslKeyFilePath(), nettyConfig.getSslManagerPwd(), nettyConfig.getSslStorePwd() )); } pipeline.addLast("idleStateHandler", new IdleStateHandler(0, 0, 60)) .addLast("httpCodec",new HttpServerCodec()) .addLast("aggregator",new HttpObjectAggregator(65535)) .addLast("compressor ", new HttpContentCompressor()) .addLast("webSocketHandler",new WebSocketServerProtocolHandler("/mqtt", MixAll.MQTT_VERSION_SUPPORT,true)) .addLast("byteBuf2WebSocketEncoder",new ByteBuf2WebSocketEncoder()) .addLast("webSocket2ByteBufDecoder",new WebSocket2ByteBufDecoder()) .addLast("mqttDecoder", new MqttDecoder(nettyConfig.getMaxMsgSize())) .addLast("mqttEncoder", MqttEncoder.INSTANCE) .addLast("nettyConnectionManager", new NettyConnectHandler(nettyEventExcutor)) .addLast("nettyMqttHandler", new NettyMqttHandler()); } }); if(nettyConfig.isPooledByteBufAllocatorEnable()){ bootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); } try { ChannelFuture future = bootstrap.bind(port).sync(); log.info("Start webSocket server {} success,port = {}", useSsl?"with ssl":"", port); }catch (InterruptedException ex){ log.error("Start webSocket server {} failure.cause={}", useSsl?"with ssl":"", ex); } }
Example 13
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 14
Source File: NettyRemotingServer.java From jmqtt with Apache License 2.0 | 4 votes |
private void startTcpServer(boolean useSsl, Integer port){ ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(selectorGroup,ioGroup) .channel(clazz) .option(ChannelOption.SO_BACKLOG, nettyConfig.getTcpBackLog()) .childOption(ChannelOption.TCP_NODELAY, nettyConfig.isTcpNoDelay()) .childOption(ChannelOption.SO_SNDBUF, nettyConfig.getTcpSndBuf()) .option(ChannelOption.SO_RCVBUF, nettyConfig.getTcpRcvBuf()) .option(ChannelOption.SO_REUSEADDR, nettyConfig.isTcpReuseAddr()) .childOption(ChannelOption.SO_KEEPALIVE, nettyConfig.isTcpKeepAlive()) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { ChannelPipeline pipeline = socketChannel.pipeline(); if (useSsl) { pipeline.addLast("ssl", NettySslHandler.getSslHandler( socketChannel, nettyConfig.isUseClientCA(), nettyConfig.getSslKeyStoreType(), brokerConfig.getJmqttHome() + nettyConfig.getSslKeyFilePath(), nettyConfig.getSslManagerPwd(), nettyConfig.getSslStorePwd() )); } pipeline.addLast("idleStateHandler", new IdleStateHandler(60, 0, 0)) .addLast("mqttEncoder", MqttEncoder.INSTANCE) .addLast("mqttDecoder", new MqttDecoder(nettyConfig.getMaxMsgSize())) .addLast("nettyConnectionManager", new NettyConnectHandler(nettyEventExcutor)) .addLast("nettyMqttHandler", new NettyMqttHandler()); } }); if(nettyConfig.isPooledByteBufAllocatorEnable()){ bootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); } try { ChannelFuture future = bootstrap.bind(port).sync(); log.info("Start tcp server {} success,port = {}", useSsl?"with ssl":"", port); }catch (InterruptedException ex){ log.error("Start tcp server {} failure.cause={}", useSsl?"with ssl":"", ex); } }
Example 15
Source File: NettyServer.java From wind-im 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 16
Source File: NettyTcpAcceptor.java From Jupiter with Apache License 2.0 | 4 votes |
@Override protected void setOptions() { super.setOptions(); ServerBootstrap boot = bootstrap(); // parent options NettyConfig.NettyTcpConfigGroup.ParentConfig parent = configGroup.parent(); boot.option(ChannelOption.SO_BACKLOG, parent.getBacklog()) .option(ChannelOption.SO_REUSEADDR, parent.isReuseAddress()) .option(EpollChannelOption.SO_REUSEPORT, parent.isReusePort()) .option(EpollChannelOption.IP_FREEBIND, parent.isIpFreeBind()) .option(EpollChannelOption.IP_TRANSPARENT, parent.isIpTransparent()); if (parent.getRcvBuf() > 0) { boot.option(ChannelOption.SO_RCVBUF, parent.getRcvBuf()); } if (parent.getPendingFastOpenRequestsThreshold() > 0) { boot.option(EpollChannelOption.TCP_FASTOPEN, parent.getPendingFastOpenRequestsThreshold()); } if (parent.getTcpDeferAccept() > 0) { boot.option(EpollChannelOption.TCP_DEFER_ACCEPT, parent.getTcpDeferAccept()); } if (parent.isEdgeTriggered()) { boot.option(EpollChannelOption.EPOLL_MODE, EpollMode.EDGE_TRIGGERED); } else { boot.option(EpollChannelOption.EPOLL_MODE, EpollMode.LEVEL_TRIGGERED); } // child options NettyConfig.NettyTcpConfigGroup.ChildConfig child = configGroup.child(); WriteBufferWaterMark waterMark = createWriteBufferWaterMark(child.getWriteBufferLowWaterMark(), child.getWriteBufferHighWaterMark()); boot.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK, waterMark) .childOption(ChannelOption.SO_REUSEADDR, child.isReuseAddress()) .childOption(ChannelOption.SO_KEEPALIVE, child.isKeepAlive()) .childOption(ChannelOption.TCP_NODELAY, child.isTcpNoDelay()) .childOption(ChannelOption.ALLOW_HALF_CLOSURE, child.isAllowHalfClosure()); if (child.getRcvBuf() > 0) { boot.childOption(ChannelOption.SO_RCVBUF, child.getRcvBuf()); } if (child.getSndBuf() > 0) { boot.childOption(ChannelOption.SO_SNDBUF, child.getSndBuf()); } if (child.getLinger() > 0) { boot.childOption(ChannelOption.SO_LINGER, child.getLinger()); } if (child.getIpTos() > 0) { boot.childOption(ChannelOption.IP_TOS, child.getIpTos()); } if (child.getTcpNotSentLowAt() > 0) { boot.childOption(EpollChannelOption.TCP_NOTSENT_LOWAT, child.getTcpNotSentLowAt()); } if (child.getTcpKeepCnt() > 0) { boot.childOption(EpollChannelOption.TCP_KEEPCNT, child.getTcpKeepCnt()); } if (child.getTcpUserTimeout() > 0) { boot.childOption(EpollChannelOption.TCP_USER_TIMEOUT, child.getTcpUserTimeout()); } if (child.getTcpKeepIdle() > 0) { boot.childOption(EpollChannelOption.TCP_KEEPIDLE, child.getTcpKeepIdle()); } if (child.getTcpKeepInterval() > 0) { boot.childOption(EpollChannelOption.TCP_KEEPINTVL, child.getTcpKeepInterval()); } if (SocketChannelProvider.SocketType.NATIVE_EPOLL == socketType()) { boot.childOption(EpollChannelOption.TCP_CORK, child.isTcpCork()) .childOption(EpollChannelOption.TCP_QUICKACK, child.isTcpQuickAck()) .childOption(EpollChannelOption.IP_TRANSPARENT, child.isIpTransparent()); if (child.isTcpFastOpenConnect()) { // Requires Linux kernel 4.11 or later boot.childOption(EpollChannelOption.TCP_FASTOPEN_CONNECT, child.isTcpFastOpenConnect()); } if (child.isEdgeTriggered()) { boot.childOption(EpollChannelOption.EPOLL_MODE, EpollMode.EDGE_TRIGGERED); } else { boot.childOption(EpollChannelOption.EPOLL_MODE, EpollMode.LEVEL_TRIGGERED); } } }
Example 17
Source File: NettyRemotingServer.java From reading-and-annotate-rocketmq-3.4.6 with GNU General Public License v3.0 | 4 votes |
@Override public void start() { this.defaultEventExecutorGroup = new DefaultEventExecutorGroup(// nettyServerConfig.getServerWorkerThreads(), // new ThreadFactory() { private AtomicInteger threadIndex = new AtomicInteger(0); @Override public Thread newThread(Runnable r) { return new Thread(r, "NettyServerCodecThread_" + this.threadIndex.incrementAndGet()); } }); ServerBootstrap childHandler = // this.serverBootstrap.group(this.eventLoopGroupBoss, this.eventLoopGroupSelector).channel(NioServerSocketChannel.class) // .option(ChannelOption.SO_BACKLOG, 1024) // .option(ChannelOption.SO_REUSEADDR, true) // .option(ChannelOption.SO_KEEPALIVE, false) // .childOption(ChannelOption.TCP_NODELAY, true) // .option(ChannelOption.SO_SNDBUF, nettyServerConfig.getServerSocketSndBufSize()) // .option(ChannelOption.SO_RCVBUF, nettyServerConfig.getServerSocketRcvBufSize()) // .localAddress(new InetSocketAddress(this.nettyServerConfig.getListenPort())) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast( // defaultEventExecutorGroup, // new NettyEncoder(), // new NettyDecoder(), // new IdleStateHandler(0, 0, nettyServerConfig.getServerChannelMaxIdleTimeSeconds()),// new NettyConnetManageHandler(), // new NettyServerHandler()); } }); if (nettyServerConfig.isServerPooledByteBufAllocatorEnable()) { childHandler.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); } try { ChannelFuture sync = this.serverBootstrap.bind().sync(); InetSocketAddress addr = (InetSocketAddress) sync.channel().localAddress(); this.port = addr.getPort(); } catch (InterruptedException e1) { throw new RuntimeException("this.serverBootstrap.bind().sync() InterruptedException", e1); } if (this.channelEventListener != null) { this.nettyEventExecuter.start(); } this.timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { try { NettyRemotingServer.this.scanResponseTable(); } catch (Exception e) { log.error("scanResponseTable exception", e); } } }, 1000 * 3, 1000); }
Example 18
Source File: NettyRemotingServer.java From RocketMQ-Master-analyze with Apache License 2.0 | 4 votes |
@Override public void start() { this.defaultEventExecutorGroup = new DefaultEventExecutorGroup(// nettyServerConfig.getServerWorkerThreads(), // new ThreadFactory() { private AtomicInteger threadIndex = new AtomicInteger(0); @Override public Thread newThread(Runnable r) { return new Thread(r, "NettyServerWorkerThread_" + this.threadIndex.incrementAndGet()); } }); ServerBootstrap childHandler = // this.serverBootstrap.group(this.eventLoopGroupBoss, this.eventLoopGroupWorker) .channel(NioServerSocketChannel.class) // .option(ChannelOption.SO_BACKLOG, 1024) // .option(ChannelOption.SO_REUSEADDR, true) // .option(ChannelOption.SO_KEEPALIVE, false) // .childOption(ChannelOption.TCP_NODELAY, true) // .option(ChannelOption.SO_SNDBUF, nettyServerConfig.getServerSocketSndBufSize()) // .option(ChannelOption.SO_RCVBUF, nettyServerConfig.getServerSocketRcvBufSize()) // .localAddress(new InetSocketAddress(this.nettyServerConfig.getListenPort())) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast( // defaultEventExecutorGroup, // new NettyEncoder(), // new NettyDecoder(), // new IdleStateHandler(0, 0, nettyServerConfig.getServerChannelMaxIdleTimeSeconds()), // new NettyConnetManageHandler(), // new NettyServerHandler()); } }); if (nettyServerConfig.isServerPooledByteBufAllocatorEnable()) { // 这个选项有可能会占用大量堆外内存,暂时不使用。 childHandler.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); } try { ChannelFuture sync = this.serverBootstrap.bind().sync(); InetSocketAddress addr = (InetSocketAddress) sync.channel().localAddress(); this.port = addr.getPort(); } catch (InterruptedException e1) { throw new RuntimeException("this.serverBootstrap.bind().sync() InterruptedException", e1); } if (this.channelEventListener != null) { this.nettyEventExecuter.start(); } // 每隔1秒扫描下异步调用超时情况 this.timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { try { NettyRemotingServer.this.scanResponseTable(); } catch (Exception e) { log.error("scanResponseTable exception", e); } } }, 1000 * 3, 1000); }
Example 19
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 20
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); } }