美文网首页Netty源码分析系列
Netty源码分析系列--5.ServerBootStrap绑定

Netty源码分析系列--5.ServerBootStrap绑定

作者: ted005 | 来源:发表于2018-11-01 00:33 被阅读120次

前文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

相关文章

网友评论

    本文标题:Netty源码分析系列--5.ServerBootStrap绑定

    本文链接:https://www.haomeiwen.com/subject/jjttxqtx.html