Netty 端口绑定解析

Netty 基于 NIO 的框架,在底层还是会使用ServerSocketChannel来绑定端口,下面看一下Netty源码调用的流程。
bind.jpg

源码片段
AbstractBootstrap#doBind0

private static void doBind0(  
        final ChannelFuture regFuture, final Channel channel,  
 final SocketAddress localAddress, final ChannelPromise promise) {  

    // This method is invoked before channelRegistered() is triggered.  Give user handlers a chance to set up  
 // the pipeline in its channelRegistered() implementation.  
 channel.eventLoop().execute(new Runnable() {  
        @Override  
  public void run() {  
            if (regFuture.isSuccess()) {  
                channel.bind(localAddress, promise).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);  
  } else {  
                promise.setFailure(regFuture.cause());  
  }  
        }  
    });  
}

这里使用EventLoop线程去执行端口的绑定。
AbstractChannelHandlerContext#invokeBind

private void invokeBind(SocketAddress localAddress, ChannelPromise promise) {  
    if (invokeHandler()) {  
        try {  
            ((ChannelOutboundHandler) handler()).bind(this, localAddress, promise);  
          } catch (Throwable t) {  
            notifyOutboundHandlerException(t, promise);  
          }  
    } else {  
        bind(localAddress, promise);  
  }  
}

这段代码执行((ChannelOutboundHandler) handler()).bind(this, localAddress, promise);代码。
这里的ChannelOutboundHandler是通知IO出站处理器操作。
NioServerSocketChannel#doBind

@Override  
protected void doBind(SocketAddress localAddress) throws Exception {  
    if (PlatformDependent.javaVersion() >= 7) {  
        javaChannel().bind(localAddress, config.getBacklog());  
  } else {  
        javaChannel().socket().bind(localAddress, config.getBacklog());  
  }  
}

这里java version 大于7, 再去看一下 JDK 的 ServerSocketChannel ,通过上面的注释可以看到这个是从1.7开始有的。

 * @since 1.7  
 */
 public final ServerSocketChannel bind(SocketAddress local)
添加新评论