netty源码(一)
netty server start
main thread
1.在实例化nioeventloopgroup的时候会创建selector
在实例化nioeventloop时会调用openSelector()方法,创建selector
2.在serverBootstrap.channel(NioServerSocketChannel.class)时会创建ReflectiveChannelFactory
并获得NioServerSocketChannel的constructor
3.在serverBootstrap.bind()中会通过前面的时会创建ReflectiveChannelFactory创建nioserversockchannel
4.init(channel)中向boss中的nioeventloop的pipeline添加ChannelInitializer
5.ChannelFuture regFuture = config().group().register(channel);
config().group()获得的是boss channel则是前面创建的nioserversockchannel
走到MultithreadEventLoopGroup中 next().register(channel);
next() 获得的是前面实例化出来的nioeventloop
之后走到SingleThreadEventLoop 的register(new DefaultChannelPromise(channel, this));
promise.channel().unsafe().register(this, promise);
if (eventLoop.inEventLoop()) {
register0(promise);
} else {
try {
eventLoop.execute(new Runnable() {
@Override
public void run() {
register0(promise);
}
});
} catch (Throwable t) {
logger.warn(
“Force-closing a channel whose registration task was not accepted by an event loop: {}”,
AbstractChannel.this, t);
closeForcibly();
closeFuture.setClosed();
safeSetFailure(promise, t);
}
}
此时当前线程还是main线程走else
新创建一个thread 跑register0(promise);
再回到register(new DefaultChannelPromise(channel, this));这个方法
ChannelFuture regFuture = config().group().register(channel);
实际上返回的regFuture就是这个 DefaultChannelPromise
initAndRegister()方法中的
ch.eventLoop().execute(new Runnable() {
@Override
public void run() {
pipeline.addLast(new ServerBootstrapAcceptor(
ch, currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs));
}
});
register
eventLoop.execute(new Runnable() {
@Override
public void run() {
register0(promise);
}
});
doBind0
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());
}
}
});
selectionKey.interestOps(interestOps | readInterestOp);