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

The following examples show how to use io.netty.bootstrap.ServerBootstrap#option() . 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: Controller.java    From onos with 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 2
Source File: AbstractNettyServer.java    From spring-boot-protocol with Apache License 2.0 6 votes vote down vote up
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 File: NettyRestServer.java    From netty-restful-server with 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 File: DefaultServer.java    From sailfish with 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 File: Http2Server.java    From netty-4.1.22 with 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 6
Source File: BGPDispatcherImpl.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
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 7
Source File: Bootstraps.java    From cantor with 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 8
Source File: AbstractServerSocketTest.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(ServerBootstrap bootstrap, ByteBufAllocator allocator) {
    addr = newSocketAddress();
    bootstrap.localAddress(addr);
    bootstrap.option(ChannelOption.ALLOCATOR, allocator);
    bootstrap.childOption(ChannelOption.ALLOCATOR, allocator);
}
 
Example 9
Source File: Controller.java    From onos with 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 10
Source File: NettyServer.java    From ob1k with 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 11
Source File: ThreadServerSocket.java    From IMServer with 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 12
Source File: AbstractSctpTest.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@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 File: SpdyServer.java    From netty-4.1.22 with 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 14
Source File: HttpHelloWorldServer.java    From tools-journey with Apache License 2.0 5 votes vote down vote up
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 15
Source File: TCPServer.java    From jt808-server with 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 16
Source File: HttpServer.java    From openzaly with 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 File: Netty4Transport.java    From crate with 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 18
Source File: Http2Server.java    From netty-4.1.22 with 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 File: NettyServerDemo.java    From NettyChat with 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 20
Source File: HttpServer.java    From wind-im with 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);
	}
}