3-3 服务端CHannel的初始化:initAndRegister

一  服务端CHannel的初始化流程

 1.  init()  //初始化入口

 2.  set ChannelOptions,ChannelAttrs

 3.  set ChildOptions,ChildAttrs

 4.  config handler  //配置服务端pipeline

 5.  add ServerBootstrapAcceptor  //添加连接器

二  

 1.  init() 流程如下

 进入 ServerBootstrap.init() 方法

    @Override
    void init(Channel channel) throws Exception {
        //第一步 保存ChannelOptions
        final Map<ChannelOption<?>, Object> options = options();
        synchronized (options) {
            channel.config().setOptions(options);
        }

        //保存ChannelAttrs
        final Map<AttributeKey<?>, Object> attrs = attrs();
        synchronized (attrs) {
            for (Entry<AttributeKey<?>, Object> e: attrs.entrySet()) {
                @SuppressWarnings("unchecked")
                AttributeKey<Object> key = (AttributeKey<Object>) e.getKey();
                channel.attr(key).set(e.getValue());
            }
        }

        ChannelPipeline p = channel.pipeline();
        if (handler() != null) {
            p.addLast(handler());
        }

        final EventLoopGroup currentChildGroup = childGroup;
        final ChannelHandler currentChildHandler = childHandler;
        final Entry<ChannelOption<?>, Object>[] currentChildOptions;
        final Entry<AttributeKey<?>, Object>[] currentChildAttrs;
        //第二步 保存childOptions
        synchronized (childOptions) {
            currentChildOptions = childOptions.entrySet().toArray(newOptionArray(childOptions.size()));
        }
        //保存childAttrs
        synchronized (childAttrs) {
            currentChildAttrs = childAttrs.entrySet().toArray(newAttrArray(childAttrs.size()));
        }
        //第三步 添加Handler(配置服务端的pipeline)
        p.addLast(new ChannelInitializer<Channel>() {
            @Override
            public void initChannel(Channel ch) throws Exception {
                //第四步 添加连接接入器ServerBootstrapAcceptor
                ch.pipeline().addLast(new ServerBootstrapAcceptor(
                        currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs));
            }
        });
    }

  

猜你喜欢

转载自www.cnblogs.com/programmlover/p/11924366.html
3-3