这里以fireChannelRead为例
AbstractNioByteChannelpublic final void read() {
ByteBuf byteBuf = null;
boolean close = false;
try {
do {
byteBuf = allocHandle.allocate(allocator);
allocHandle.lastBytesRead(doReadBytes(byteBuf)); //不断调用doReadBytes
if (allocHandle.lastBytesRead() <= 0) {
// nothing was read. release the buffer.
byteBuf.release();
byteBuf = null;
close = allocHandle.lastBytesRead() < 0;
if (close) {
// There is nothing left to read as we received an EOF.
readPending = false;
}
break;
}
allocHandle.incMessagesRead(1);
readPending = false;
pipeline.fireChannelRead(byteBuf); // 读到入口触发pipeline的fireChannelRead
byteBuf = null; // 读完设置null
} while (allocHandle.continueReading());
allocHandle.readComplete();
pipeline.fireChannelReadComplete();
if (close) {
closeOnRead(pipeline);
}
}
入口
DefaultChannelPipeline
从head开始调用
public final ChannelPipeline fireChannelRead(Object msg) {
AbstractChannelHandlerContext.invokeChannelRead(head, msg); // DefaultChannelPipeline的fireChannelRead 从head开始
return this;
}
invokeChannelRead
AbstractChannelHandlerContext
static void invokeChannelRead(final AbstractChannelHandlerContext next, Object msg) {
final Object m = next.pipeline.touch(ObjectUtil.checkNotNull(msg, "msg"), next); // accetp-event=NioSocketChannel
EventExecutor executor = next.executor(); // AbstractChannelHandlerContext
if (executor.inEventLoop()) {
next.invokeChannelRead(m); // 出发下一个invokeChannelRead
} else {
executor.execute(new Runnable() {
@Override
public void run() {
next.invokeChannelRead(m);
}
});
}
}
invokeChannelRead
AbstractChannelHandlerContext
private void invokeChannelRead(Object msg) { //msg=NioSocketChannel
if (invokeHandler()) { // AbstractChannelHandlerContext
try {
((ChannelInboundHandler) handler()).channelRead(this, msg);
} catch (Throwable t) {
notifyHandlerException(t);
}
} else {
fireChannelRead(msg);
}
}
channelRead
DefaultChannelPipeline
public void channelRead(ChannelHandlerContext ctx, Object msg) {
ctx.fireChannelRead(msg); // 这里是HeadContext.channelRead
}
fireChannelRead
AbstractChannelHandlerContext
1个1个往下调用
public ChannelHandlerContext fireChannelRead(final Object msg) { // AbstractChannelHandlerContext
invokeChannelRead(findContextInbound(MASK_CHANNEL_READ), msg); // 得到下一个的READ channelRead
return this;
}
findContextInbound
找下一个ChannelHandler
private AbstractChannelHandlerContext findContextInbound(int mask) {
AbstractChannelHandlerContext ctx = this;
do {
ctx = ctx.next;
} while ((ctx.executionMask & mask) == 0); // 如果下一个Handler的某个事件,标注@Skip的会被跳过 继续寻找下一个
return ctx;
}