netty服务端启动原理

 public static void main(String[] args) throws InterruptedException {
            ServerBootstrap b = new ServerBootstrap();
            EventLoopGroup bossGroup = new NioEventLoopGroup();
            EventLoopGroup workerGroup = new NioEventLoopGroup();
            try {
                b.group(bossGroup, workerGroup);
                b.channel(NioServerSocketChannel.class);
                b.childOption(ChannelOption.TCP_NODELAY, true);
                b.childHandler(new NettyServerFilter()); //设置过滤器
                // 服务器绑定端口监听
                ChannelFuture f = b.bind(port).sync();
                System.out.println("服务端启动成功...");
                // 监听服务器关闭监听
                f.channel().closeFuture().sync();
            } finally {
                bossGroup.shutdownGracefully(); ////关闭EventLoopGroup,释放掉所有资源包括创建的线程
                workerGroup.shutdownGracefully();
            }
        }

【创建服务端channel】

ChannelFuture f = b.bind(port).sync();
    ChannelFuture regPromise = this.initAndRegister();//初始化并注册
        Channel channel = this.channelFactory().newChannel();//创建服务端Channel
        //其实是创建NioServerSocketChannel类,在b.channel(NioServerSocketChannel.class)设置到AbstractBootstrap中
            NioServerSocketChannel构造函数:super((Channel)null, newSocket(), 16);//newSocket()调用jdk底层provider创建ServerSocketChannel
                this.unsafe = this.newUnsafe();
                this.pipeline = new DefaultChannelPipeline(this);
                ch.configureBlocking(false); //设置服务端channel非阻塞

【初始化服务端channel】

ChannelFuture regPromise = this.initAndRegister();//初始化并注册
    this.init(channel);
        channel.config().setOptions(options); //设置用户定义的options,b.childOption(ChannelOption.TCP_NODELAY, true);
        channel.attr(key).set(e.getValue());//设置用户定义的attr
        p.addLast(new ChannelHandler[]{this.handler()});//pipeline设置用户定义的handler,b.childHandler(new NettyServerFilter());
        ch.pipeline().addLast(new ChannelHandler[]{new ServerBootstrap.ServerBootstrapAcceptor(currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs)});

【注册channel到selector】

ChannelFuture regPromise = this.initAndRegister();//初始化并注册
    this.init(channel);
        this.group().register(channel, regPromise);
            register0() 
                doRegister()//调用jdk注册

【端口绑定】

ChannelFuture f = b.bind(port).sync();
     doBind0(regPromise, channel, localAddress, promise);
        channel.bind(localAddress, promise).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);//调用jdk

你可能感兴趣的:(java)