netty学习9:ServerBootstrap.bind源码分析

简单概括就是 创建NioServerSocketChannel对象 、绑定端口、启动bossGroup线程等等

io.netty.bootstrap.AbstractBootstrap#doBind

private ChannelFuture doBind(final SocketAddress localAddress) {
        final ChannelFuture regFuture = initAndRegister();//初始化注册
        final Channel channel = regFuture.channel();
        if (regFuture.cause() != null) {
            return regFuture;
        }

        if (regFuture.isDone()) {//注册完成
            // At this point we know that the registration was complete and successful.
            ChannelPromise promise = channel.newPromise();
            doBind0(regFuture, channel, localAddress, promise);//绑定
            return promise;
        } else {
            // Registration future is almost always fulfilled already, but just in case it's not.
            final PendingRegistrationPromise promise = new PendingRegistrationPromise(channel);
            regFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    Throwable cause = future.cause();
                    if (cause != null) {
                        // Registration on the EventLoop failed so fail the ChannelPromise directly to not cause an
                        // IllegalStateException once we try to access the EventLoop of the Channel.
                        promise.setFailure(cause);
                    } else {
                        // Registration was successful, so set the correct executor to use.
                        // See https://github.com/netty/netty/issues/2586
                        promise.registered();

                        doBind0(regFuture, channel, localAddress, promise);
                    }
                }
            });
            return promise;
        }
    }



//初始化and注册
    final ChannelFuture initAndRegister() {
        Channel channel = null;
        try {
            channel = channelFactory.newChannel();//newInstance反射调用NioServerSocketChannel|NioSocketChannel的无参构造方法
            //初始化 pipeline里面设置ServerBootstrapAcceptor的handler 就是用来把bossGroup接收到的accept请求转发给workGroup线程去处理
            init(channel);
        } catch (Throwable t) {
            if (channel != null) {
                // channel can be null if newChannel crashed (eg SocketException("too many open files"))
                channel.unsafe().closeForcibly();
                // as the Channel is not registered yet we need to force the usage of the GlobalEventExecutor
                return new DefaultChannelPromise(channel, GlobalEventExecutor.INSTANCE).setFailure(t);
            }
            // as the Channel is not registered yet we need to force the usage of the GlobalEventExecutor
            return new DefaultChannelPromise(new FailedChannel(), GlobalEventExecutor.INSTANCE).setFailure(t);
        }
        //往bossGroup里面注册channel 最终调用unsafe注册
        ChannelFuture regFuture = config().group().register(channel);
        if (regFuture.cause() != null) {
            if (channel.isRegistered()) {
                channel.close();
            } else {
                channel.unsafe().closeForcibly();
            }
        }
        return regFuture;
    }

io.netty.bootstrap.ServerBootstrap#init

 

void init(Channel channel) {//channel 是NioServerSocketChannel
        setChannelOptions(channel, newOptionsArray(), logger);
        setAttributes(channel, newAttributesArray());

        ChannelPipeline p = channel.pipeline();//pipeline在调用构造函数时候创建即DefaultChannelPipeline pipeline即handler组成的责任链

        final EventLoopGroup currentChildGroup = childGroup;//childGroup即workGroup
        final ChannelHandler currentChildHandler = childHandler;//childHandler即main方法里面childHandler设置的Handler处理器
        final Entry<ChannelOption<?>, Object>[] currentChildOptions = newOptionsArray(childOptions);//childOptions设置的属性
        final Entry<AttributeKey<?>, Object>[] currentChildAttrs = newAttributesArray(childAttrs);//childAttr设置的属性
        //pipeline即链表组成的责任链 addlast即添加到链表尾部  initChannel等待回调
        p.addLast(new ChannelInitializer<Channel>() {
            @Override
            public void initChannel(final Channel ch) {
                final ChannelPipeline pipeline = ch.pipeline();//ch还是NioSeverSocketChannel
                ChannelHandler handler = config.handler();
                if (handler != null) {
                    pipeline.addLast(handler);
                }

                //netty重写了execute方法 io.netty.util.concurrent.SingleThreadEventExecutor.execute(java.lang.Runnable)
                // 这时做了两件事:1.添加任务队列到taskQueue,2启动BossGroup线程自旋然后再处理taskQueue的run方法 也就是在bossGroup的线程中 执行的run方法并将ServerBootstrapAcceptor添加到pipeline当中 等待后续回调
                ch.eventLoop().execute(new Runnable() {
                    @Override
                    public void run() {
                        //异步往pipeline中添加新的handler 在创建ServerBootstrapAcceptor对象时候  传入了childGroup以及childHandler等等参数
                        pipeline.addLast(new ServerBootstrapAcceptor(
                                ch, currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs));
                    }
                });
            }
        });
    }

总结如下:

1、反射调用NioServerSocketChannel的无参构造方法 创建该对象

2、bossGroup的pipeline中添加handler 包括ServerBootstrapAcceptor 前文已介绍

3、注册感兴趣的事件给NioServerSocketChannel

4、启动bossGroup线程

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值