Netty隨記之ChannelHandlerContext與Channel的writeAndFlush的區別
ChannelHandlerContext的writeAndFlush方法會將數據寫到ChannelPipeline中當前ChannelHandler的下一個ChannelHandler開始處理。
ChannelHandlerContext#writeAndFlush實現源碼:
private void write(Object msg, boolean flush, ChannelPromise promise) {
AbstractChannelHandlerContext next = findContextOutbound();
final Object m = pipeline.touch(msg, next);
EventExecutor executor = next.executor();
if (executor.inEventLoop()) {
if (flush) {
next.invokeWriteAndFlush(m, promise);
} else {
next.invokeWrite(m, promise);
}
} else {
AbstractWriteTask task;
if (flush) {
task = WriteAndFlushTask.newInstance(next, m, promise);
} else {
task = WriteTask.newInstance(next, m, promise);
}
safeExecute(executor, task, promise, m);
}
}
private AbstractChannelHandlerContext findContextOutbound() {
AbstractChannelHandlerContext ctx = this;
do {
ctx = ctx.prev;
} while (!ctx.outbound);
return ctx;
}
Channel的writeAndFlush方法會將數據寫到ChannelPipeline中最後一個ChannelHandler然後數據從尾部開始向頭部方向流動會經過所有的ChannelHandler, ChannelPipeline中的所有ChannelHandler都可以處理數據。
public final ChannelFuture writeAndFlush(Object msg) {
return tail.writeAndFlush(msg);
}
最後更新:2017-06-08 18:01:29