Netty服務(wù)器主程序樣例分析

public class MyServer {

    public static void main(String[] args) throws InterruptedException {
        /*
            NioEventLoopGroup如果調(diào)用的是無(wú)參的構(gòu)造函數(shù),會(huì)默認(rèn)線程數(shù)為0,
            最后通過(guò)三目運(yùn)算(nThreads == 0 ? DEFAULT_EVENT_LOOP_THREADS : nThreads)進(jìn)行轉(zhuǎn)換,
            即如果沒(méi)有指定線程數(shù)的大小,其值就是下面的默認(rèn)值(會(huì)根據(jù)系統(tǒng)配置進(jìn)行求值,比如我是四核的,得到的線程數(shù)就是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完成對(duì)bootstrap的賦值操作
            serverBootstrap.group(boosGroup,workerGroup)
                    //通過(guò)channelFactory生成bind()的channel
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new MyServerInitializer());


            /*
                1. init channel
                ——————————————————————————————————————————————————————————————————————————
                     p.addLast(new ChannelInitializer<Channel>() {
                        @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();
        }
    }

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容