美文网首页
Netty随记--ChannelHandlerContext与C

Netty随记--ChannelHandlerContext与C

作者: henry技术探索记录员 | 来源:发表于2019-03-19 16:55 被阅读0次

ChannelHandlerContext的writeAndFlush方法会将数据写到ChannelPipeline中当前ChannelHandler的下一个ChannelHandler开始处理。

1. 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;
    }
2. Channel的writeAndFlush方法会将数据写到ChannelPipeline中最后一个ChannelHandler然后数据从尾部开始向头部方向流动会经过所有的ChannelHandler, ChannelPipeline中的所有ChannelHandler都可以处理数据。
public final ChannelFuture writeAndFlush(Object msg) {
        return tail.writeAndFlush(msg);
    }

参考https://yq.aliyun.com/articles/97500
参考http://blog.csdn.net/wm3418925/article/details/54864177

相关文章

网友评论

      本文标题:Netty随记--ChannelHandlerContext与C

      本文链接:https://www.haomeiwen.com/subject/iqmvpqtx.html