Java Code Examples for io.netty.bootstrap.ServerBootstrap#option()

The following examples show how to use io.netty.bootstrap.ServerBootstrap#option() . These examples are extracted from open source projects. 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
private synchronized ServerBootstrap createServerBootstrap(final ChannelPipelineInitializer<?> initializer) {
    final ServerBootstrap serverBootstrap = new ServerBootstrap();
    if (Epoll.isAvailable()) {
        serverBootstrap.channel(EpollServerSocketChannel.class);
        serverBootstrap.childOption(EpollChannelOption.EPOLL_MODE, EpollMode.LEVEL_TRIGGERED);
    } else {
        serverBootstrap.channel(NioServerSocketChannel.class);
    }
    final ChannelHandler serverChannelHandler = BGPChannel.createServerChannelHandler(initializer);
    serverBootstrap.childHandler(serverChannelHandler);

    serverBootstrap.option(ChannelOption.SO_BACKLOG, SOCKET_BACKLOG_SIZE);
    serverBootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    serverBootstrap.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK, WATER_MARK);

    // Make sure we are doing round-robin processing
    serverBootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, RECV_ALLOCATOR);

    if (serverBootstrap.config().group() == null) {
        serverBootstrap.group(this.bossGroup, this.workerGroup);
    }
    return serverBootstrap;
}
 
Example 2
protected void config(ServerBootstrap bootstrap) throws Exception{
        //允许在同一端口上启动同一服务器的多个实例,只要每个实例捆绑一个不同的本地IP地址即可
        bootstrap.option(ChannelOption.SO_REUSEADDR, true)
                //netty boos的默认内存分配器
//                    .option(ChannelOption.ALLOCATOR, ByteBufAllocatorX.INSTANCE)
                //用于构造服务端套接字ServerSocket对象,标识当服务器请求处理线程全满时,用于临时存放已完成三次握手的请求的队列的最大长度
//                    .option(ChannelOption.SO_BACKLOG, 1024) // determining the number of connections queued

                //禁用Nagle算法,即数据包立即发送出去 (在TCP_NODELAY模式下,假设有3个小包要发送,第一个小包发出后,接下来的小包需要等待之前的小包被ack,在这期间小包会合并,直到接收到之前包的ack后才会发生)
//                    .childOption(ChannelOption.TCP_NODELAY, true)
                //开启TCP/IP协议实现的心跳机制
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                //netty的work默认内存分配器
                .childOption(ChannelOption.ALLOCATOR, ByteBufAllocatorX.INSTANCE);
//              .childOption(ChannelOption.ALLOCATOR, ByteBufAllocator.DEFAULT);

        if(enableEpoll){
            //允许使用同一个端口, 内核实现的负载均衡. 需要 Linux kernel >= 3.9
            bootstrap.option(UnixChannelOption.SO_REUSEPORT, true);
        }
    }
 
Example 3
Source Project: netty-restful-server   File: NettyRestServer.java    License: MIT License 6 votes vote down vote up
public void start() {
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, 1024);
        b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ServerInitializer());

        Channel ch = b.bind(Config.getInt("server.port")).sync().channel();

        ch.closeFuture().sync();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
Example 4
Source Project: sailfish   File: DefaultServer.java    License: Apache License 2.0 6 votes vote down vote up
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 5
Source Project: cantor   File: Bootstraps.java    License: Apache License 2.0 6 votes vote down vote up
public static ServerBootstrap serverBootstrap(EventLoopGroup acceptors,
                                              EventLoopGroup workers) {

    ServerBootstrap bootstrap = new ServerBootstrap().group(acceptors, workers)
                                                     .childOption(ChannelOption.TCP_NODELAY,
                                                                  true)
                                                     .childOption(ChannelOption.ALLOCATOR,
                                                                  PooledDirectByteBufAllocator.INSTANCE)
                                                     .childOption(ChannelOption.SO_KEEPALIVE,
                                                                  false)
                                                     .option(ChannelOption.SO_REUSEADDR,
                                                             true);

    bootstrap.channel(NioServerSocketChannel.class);
    bootstrap.option(ChannelOption.WRITE_BUFFER_WATER_MARK,
                     new WriteBufferWaterMark(32 * 1024, 128 * 1024));

    return bootstrap;
}
 
Example 6
Source Project: netty-4.1.22   File: Http2Server.java    License: Apache License 2.0 6 votes vote down vote up
void run() throws Exception {
    // Configure the server.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, 1024);
        b.group(group)
                .channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new Http2ServerInitializer());

        Channel ch = b.bind(port).sync().channel();

        ch.closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}
 
Example 7
Source Project: onos   File: Controller.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Accepts incoming connections.
 */
private void startAcceptingConnections() throws InterruptedException {
    if (cg == null) {
        return;
    }
    final ServerBootstrap b = new ServerBootstrap();

    b.group(bossGroup, workerGroup).channel(serverChannelClass)
            .childHandler(new OvsdbChannelInitializer(this, sslContext));
    b.option(ChannelOption.SO_REUSEADDR, true);
    b.option(ChannelOption.SO_BACKLOG, 128);
    b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    b.childOption(ChannelOption.SO_SNDBUF, Controller.SEND_BUFFER_SIZE);
    b.childOption(ChannelOption.SO_KEEPALIVE, true);

    cg.add(b.bind(ovsdbPort).syncUninterruptibly().channel());
}
 
Example 8
Source Project: jt808-server   File: TCPServer.java    License: Apache License 2.0 5 votes vote down vote up
private void bind() throws Exception {
    this.bossGroup = new NioEventLoopGroup();
    this.workerGroup = new NioEventLoopGroup();
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(bossGroup, workerGroup);
    serverBootstrap.channel(NioServerSocketChannel.class);
    serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast("idleStateHandler", new IdleStateHandler(30, 0, 0, TimeUnit.MINUTES));
            // 1024表示单条消息的最大长度,解码器在查找分隔符的时候,达到该长度还没找到的话会抛异常
            ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, Unpooled.wrappedBuffer(new byte[]{delimiter}), Unpooled.wrappedBuffer(new byte[]{delimiter, delimiter})));
            ch.pipeline().addLast(inboundHandler);
        }
    });
    serverBootstrap.option(ChannelOption.SO_BACKLOG, 128);
    serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);

    this.log.info("TCP服务启动完毕,port={}", this.port);
    ChannelFuture channelFuture = serverBootstrap.bind(port).sync();

    channelFuture.channel().closeFuture().sync();
}
 
Example 9
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;
    }

    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, 1024);
        b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new HttpHelloWorldServerInitializer(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 10
Source Project: netty-4.1.22   File: SpdyServer.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // Configure SSL.
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    SslContext sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey())
        .applicationProtocolConfig(new ApplicationProtocolConfig(
                    Protocol.NPN,
                    // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers.
                    SelectorFailureBehavior.NO_ADVERTISE,
                    // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers.
                    SelectedListenerFailureBehavior.ACCEPT,
                    ApplicationProtocolNames.SPDY_3_1,
                    ApplicationProtocolNames.HTTP_1_1))
        .build();

    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, 1024);
        b.group(bossGroup, workerGroup)
         .channel(NioServerSocketChannel.class)
         .handler(new LoggingHandler(LogLevel.INFO))
         .childHandler(new SpdyServerInitializer(sslCtx));

        Channel ch = b.bind(PORT).sync().channel();

        System.err.println("Open your SPDY-enabled web browser and navigate to https://127.0.0.1:" + PORT + '/');
        System.err.println("If using Chrome browser, check your SPDY sessions at chrome://net-internals/#spdy");

        ch.closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
Example 11
@Override
protected void configure(ServerBootstrap bootstrap, ByteBufAllocator allocator) {
    addr = newSocketAddress();
    bootstrap.localAddress(addr);
    bootstrap.option(ChannelOption.ALLOCATOR, allocator);
    bootstrap.childOption(ChannelOption.ALLOCATOR, allocator);
}
 
Example 12
@Override
protected void configure(ServerBootstrap serverBootstrap, Bootstrap bootstrap, ByteBufAllocator allocator) {
    addr = new InetSocketAddress(NetUtil.LOCALHOST, TestUtils.getFreePort());
    serverBootstrap.localAddress(addr);
    serverBootstrap.option(ChannelOption.ALLOCATOR, allocator);
    serverBootstrap.childOption(ChannelOption.ALLOCATOR, allocator);
    bootstrap.remoteAddress(addr);
    bootstrap.option(ChannelOption.ALLOCATOR, allocator);
}
 
Example 13
Source Project: IMServer   File: ThreadServerSocket.java    License: Apache License 2.0 5 votes vote down vote up
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 Project: ob1k   File: NettyServer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
  public InetSocketAddress start() {
    logger.info("################## Starting OB1K server for module '{}' ##################", applicationName);
    try {
      final ServerBootstrap b = new ServerBootstrap();
      b.option(ChannelOption.SO_BACKLOG, 1024);
      b.option(ChannelOption.SO_RCVBUF, 64 * 1024);
      b.childOption(ChannelOption.SO_SNDBUF, 64 * 1024);
      // it means that the max static file can be 1024*ResourceRegion.BUFFER_SIZE = 64Mb
      b.childOption(ChannelOption.WRITE_SPIN_COUNT, 1024);
      b.childOption(ChannelOption.TCP_NODELAY, true);
      b.group(nioGroup)
          .channel(NioServerSocketChannel.class)
          .childHandler(new RPCServerInitializer(maxContentLength));

      channel = b.bind(port).sync().channel();
      addShutdownhook();
      // TEMP disable till I get an answer to https://groups.google.com/d/topic/netty/uY4n1Wjmpvs/discussion
//      NettyQueuesGaugeBuilder.registerQueueGauges(metricFactory, nioGroup, applicationName);

      final InetSocketAddress address = (InetSocketAddress) channel.localAddress();
      onStarted();
      logger.info("server is up and bounded on address: {}{}", address, getOpeningText());
      return address;
    } catch (final Exception e) {
      logger.error("failed to start server", e);
      return null;
    }
  }
 
Example 15
Source Project: onos   File: Controller.java    License: Apache License 2.0 5 votes vote down vote up
private void addListeningPorts(Collection<Integer> ports) {
        if (cg == null) {
            return;
        }
        final ServerBootstrap bootstrap = createServerBootStrap();
        bootstrap.option(ChannelOption.SO_REUSEADDR, true);
        bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
        bootstrap.childOption(ChannelOption.TCP_NODELAY, true);
        bootstrap.childOption(ChannelOption.SO_SNDBUF, Controller.SEND_BUFFER_SIZE);
//            bootstrap.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK,
//                                  new WriteBufferWaterMark(8 * 1024, 32 * 1024));

        bootstrap.childHandler(new OFChannelInitializer(this, null, sslContext));

        Set<Integer> existingPorts = cg.stream()
                .map(Channel::localAddress)
                .filter(InetSocketAddress.class::isInstance)
                .map(InetSocketAddress.class::cast)
                .map(InetSocketAddress::getPort)
                .collect(Collectors.toSet());
        ports.removeAll(existingPorts);

        ports.forEach(port -> {
            // TODO revisit if this is best way to listen to multiple ports
            cg.add(bootstrap.bind(port).syncUninterruptibly().channel());
            log.info("Listening for OF switch connections on {}", port);
        });
    }
 
Example 16
Source Project: wind-im   File: HttpServer.java    License: Apache License 2.0 4 votes vote down vote up
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 17
Source Project: NettyChat   File: NettyServerDemo.java    License: Apache License 2.0 4 votes vote down vote up
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 18
Source Project: netty-4.1.22   File: Http2Server.java    License: Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
        SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey())
            .sslProvider(provider)
            /* NOTE: the cipher filter may not include all ciphers required by the HTTP/2 specification.
             * Please refer to the HTTP/2 specification for cipher requirements. */
            .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
            .applicationProtocolConfig(new ApplicationProtocolConfig(
                Protocol.ALPN,
                // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers.
                SelectorFailureBehavior.NO_ADVERTISE,
                // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers.
                SelectedListenerFailureBehavior.ACCEPT,
                ApplicationProtocolNames.HTTP_2,
                ApplicationProtocolNames.HTTP_1_1))
            .build();
    } else {
        sslCtx = null;
    }
    // Configure the server.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, 1024);
        b.group(group)
         .channel(NioServerSocketChannel.class)
         .handler(new LoggingHandler(LogLevel.INFO))
         .childHandler(new Http2ServerInitializer(sslCtx));

        Channel ch = b.bind(PORT).sync().channel();

        System.err.println("Open your HTTP/2-enabled web browser and navigate to " +
                (SSL? "https" : "http") + "://127.0.0.1:" + PORT + '/');

        ch.closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}
 
Example 19
Source Project: crate   File: Netty4Transport.java    License: Apache License 2.0 4 votes vote down vote up
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 20
Source Project: openzaly   File: HttpServer.java    License: Apache License 2.0 4 votes vote down vote up
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);
	}
}