在 Netty 示例中使用 ctx.read() 与 ctx.channel.read()

Use of ctx.read() vs. ctx.channel.read() in Netty Examples

Netty 的流水线(即 ctx.foo() vs ctx.channel.foo())之前在 Whosebug 上解释过两次:

  1. Any difference between ctx.write() and ctx.channel().write() in netty?
  2. In Netty 4, what's the difference between ctx.close and ctx.channel.close?

但是,我不明白 Netty 的示例背后的直觉,即何时使用不同的方法:

public void channelActive(ChannelHandlerContext ctx) {
    ctx.read(); // <----- HERE
}

public void channelRead(final ChannelHandlerContext ctx, Object msg) {
    inboundChannel.writeAndFlush(msg).addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture future) {
            if (future.isSuccess()) {
                ctx.channel().read(); // <----- HERE
            } else {
                future.channel().close();
            }
        }
    });
}

View source on GitHub


为什么在代理实现的channelActive处理程序中使用'from this handler down'样式read,而在[=18]中使用'from the top'样式read =]?

当使用 ChannelHandlerContext.read() 时,它将从 ChannelPipelineChannelHandler 所在的点开始。当您使用 Channel.read() 时,它将从 ChannelPipeline 的尾部开始,因此需要以更糟糕的方式遍历整个 ChannelPipeline

此示例在 channelActive(...) 中使用 ctx.read() 而在 ChannelFutureListener 中使用 channel.read() 的原因是因为 ChannelFutureListener 不是 [= 的一部分12=] 所以它需要从 ChannelPipeline 的尾部开始。还要注意这里的 Channel 是不同的。