Netty服务器主程序样例分析

public class MyServer {

    public static void main(String[] args) throws InterruptedException {
        /*
            NioEventLoopGroup如果调用的是无参的构造函数,会默认线程数为0,
            最后通过三目运算(nThreads == 0 ? DEFAULT_EVENT_LOOP_THREADS : nThreads)进行转换,
            即如果没有指定线程数的大小,其值就是下面的默认值(会根据系统配置进行求值,比如我是四核的,得到的线程数就是16):
            DEFAULT_EVENT_LOOP_THREADS = Math.max(1, SystemPropertyUtil.getInt(
                "io.netty.eventLoopThreads", NettyRuntime.availableProcessors() * 2));

         */
        EventLoopGroup boosGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try{
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            //group完成对bootstrap的赋值操作
            serverBootstrap.group(boosGroup,workerGroup)
                    //通过channelFactory生成bind()的channel
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new MyServerInitializer());


            /*
                1. init channel
                ——————————————————————————————————————————————————————————————————————————
                     p.addLast(new ChannelInitializer() {
                        @Override
                        public void initChannel(final Channel ch) {
                            final ChannelPipeline pipeline = ch.pipeline();
                            //父类的handler
                            ChannelHandler handler = config.handler();
                            if (handler != null) {
                                pipeline.addLast(handler);
                            }

                            ch.eventLoop().execute(new Runnable() {
                                @Override
                                public void run() {
                                    pipeline.addLast(new ServerBootstrapAcceptor(
                                            ch, currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs));
                                }
                            });
                        }
                    });

               ————————————————————————————————————————————————————————————————————————————

             */
            ChannelFuture channelFuture = serverBootstrap.bind(8899).sync();
            channelFuture.channel().closeFuture().sync();
        }finally {
            boosGroup.shutdownGracefully().sync();
            workerGroup.shutdownGracefully().sync();
        }
    }

}

你可能感兴趣的:(Netty服务器主程序样例分析)