Netty源碼分析系列--5.ServerBootStrap綁定端口號

前文Netty源碼分析系列--3. 服務器啟動ServerBootStrap分析中介紹了對ServerBootStrap的多個變量賦值后,下一步就要綁定端口號啟動服務器。

    ChannelFuture channelFuture = serverBootstrap.bind(8899).sync();

調用bind(8899)進入抽象類AbstractBootStrapdoBind方法:

 private ChannelFuture doBind(final SocketAddress localAddress) {
    final ChannelFuture regFuture = initAndRegister();
    final Channel channel = regFuture.channel();
    if (regFuture.cause() != null) {
        return regFuture;
    }

    if (regFuture.isDone()) {
        ChannelPromise promise = channel.newPromise();
        doBind0(regFuture, channel, localAddress, promise);
        return promise;
    } else {
        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) {
                    promise.setFailure(cause);
                } else {
                    promise.registered();
                    doBind0(regFuture, channel, localAddress, promise);
                }
            }
        });
        return promise;
    }
}

其中關鍵的方法是:

  • intAndRegister()
  • ChannelFuture類型的對象regFuture添加監聽器,當IO操作完成時執行回調方法operationComplete

1 . 先關注第1行initAndRegister方法如下:其中channelFactory.newChannel()就是使用之前channel方法中創建的ReflectiveChannelFactory通過反射新建NioServerSocketChannel實例。

  final ChannelFuture initAndRegister() {
    Channel channel = null;
    try {
        channel = channelFactory.newChannel();
        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);
    }

    ChannelFuture regFuture = config().group().register(channel);
    if (regFuture.cause() != null) {
        if (channel.isRegistered()) {
            channel.close();
        } else {
            channel.unsafe().closeForcibly();
        }
    }

    return regFuture;
  }

NioServerSocketChannel類的構造函數:靜態變量DEFAULT_SELECTOR_PROVIDER使用了NIO Selector Provider,構造函數中調用靜態方法newSocket

使用provider.openServerSocketChannel()創建NioServerSocketChannel

    private static final SelectorProvider DEFAULT_SELECTOR_PROVIDER = SelectorProvider.provider();
   
    private static ServerSocketChannel newSocket(SelectorProvider provider) {
      try {
          return provider.openServerSocketChannel();
       } catch (IOException e) {
          throw new ChannelException(
                "Failed to open a server socket.", e);
      }
     }
     public NioServerSocketChannel() {
           this(newSocket(DEFAULT_SELECTOR_PROVIDER));
    }

2. initAndRegister中使用ChannelFactory創建完Channel后,調用了init進行初始化。

  void init(Channel channel) throws Exception {

    //以上省略......
    ChannelPipeline p = channel.pipeline();

    final EventLoopGroup currentChildGroup = childGroup;
    final ChannelHandler currentChildHandler = childHandler;
     //省略部分代碼......

    p.addLast(new ChannelInitializer<Channel>() {
        @Override
        public void initChannel(final Channel ch) throws Exception {
            final ChannelPipeline pipeline = ch.pipeline();
            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));
                }
            });
        }
    });
}

獲得channel對象的pipleline,如果有配置handler對象如LoggingHandler(LogLevel.INFO),會加入到pipeline中。

注意:這里出現了一個類ServerBootstrapAcceptor,稍后會介紹。

3. initAndRegister中:

   ChannelFuture regFuture = config().group().register(channel);

上面代碼group()獲得bossGroup對象,并將channel注冊到該EventLoopGroup

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容