本文记录ServerBootstrap.bind(PORT)的过程
最先做的ChannelFuture regFuture = initAndRegister();
final ChannelFuture initAndRegister() {
final Channel channel = channelFactory().newChannel();
try {
init(channel);
} catch (Throwable t) {
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);
}
...
channel是初始化NioServerSocketChannel对象
init(NioServerSocketChannel对象)
初始化的工作有创建DefaultChannelHandlerContext,DefaultChannelPipeline,DefaultServerSocketChannelConfig 把设置的ChannelOption添加到DefaultServerSocketChannelConfig,最后在channelPipeline中添加ServerBootstrapAcceptor,
初始化过程出错的处理
try {
init(channel);
} catch (Throwable t) {
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);
}
channel.unsafe()返回NioMessageUnsafe,最终调用
@Override
protected void doClose() throws Exception {
javaChannel().close();
}
关闭ServerSocketChannel通道,返回一个 result = new CauseHolder(cause)的DefaultChannelPromise出入的Executor为GlobalEventExecutor单例模式
初始化NioServerSocketChannel对象后,下一步把channel注册到NioEventLoopGroup(主)
@Override
public ChannelFuture register(Channel channel) {
return next().register(channel);
}
next()为chooser数组里选个NioEventLoop对象,也就是NioEventLoop的register(channel);
@Override
public ChannelFuture register(Channel channel) {
return register(channel, new DefaultChannelPromise(channel, this));
}
此处产生了DefaultChannelPromise
@Override
public ChannelFuture register(Channel channel) {
return register(channel, new DefaultChannelPromise(channel, this));
}
@Override
public ChannelFuture register(final Channel channel, final ChannelPromise promise) {
if (channel == null) {
throw new NullPointerException("channel");
}
if (promise == null) {
throw new NullPointerException("promise");
}
channel.unsafe().register(this, promise);
return promise;
}
channel.unsafe()就是NioServerSocketChannel的newUnsafe方法得到NioMessageUnsafe
@Override
protected AbstractNioUnsafe newUnsafe() {
return new NioMessageUnsafe();
}
AbstractBootstrap接着把NioServerSocketChannel注册到EventLoop上
ChannelFuture regFuture = group().register(channel);
if (regFuture.cause() != null) {
if (channel.isRegistered()) {
channel.close();
} else {
channel.unsafe().closeForcibly();
}
}
由EventLoop的父类SingleThreadEventLoop调用 channel.unsafe().register(this, promise);注册,promise是在此处new出new DefaultChannelPromise(channel, this);EventLoop和NioSocketChannelChannel构建到Promise
NioMessageUnsafe 注册 promise和EventLoop下一文在看