使用Netty中的例子ctx.read()与ctx.channel.read()

使用Netty中的例子ctx.read()与ctx.channel.read()

问题描述:

Netty中的流水线(即ctx.foo() VS ctx.channel.foo())已经在计算器上过两次解释说:使用Netty中的例子ctx.read()与ctx.channel.read()

  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处理代理IMPL的风格read,但使用“从顶部”的风格readchannelRead

使用ChannelHandlerContext.read()时,它将从ChannelPipeline中的ChannelHandler所在的点开始。当您使用Channel.read()时,它将从ChannelPipeline的尾部开始,因此需要遍布整个ChannelPipeline,投下较差的阵容。

之所以出现这种例子在ChannelFutureListener使用ctx.read()channelActive(...)channel.read()是因为ChannelFutureListener不是ChannelHandler的一部分,所以它需要在ChannelPipeline的尾部开始。另外请注意,这里的Channel不一样。

+0

我还没有完全理解这一点。当你说“它将从处理程序所在的管道中的点开始”时,后续处理程序正在调用什么。 AFAIK当你调用'.read()'时,你所要做的就是要求套接字读取一些数据......然后如果/当数据到达时,'channelRead'将在流水线的_start_处被触发。或者当你调用'ctx.read()'时,如果/当数据到达时,前面的处理程序是否没有收到任何数据? –

+1

如果你在'ChannelPipeline'中有'ChannelOutboundHandler',它们有'read(...)'回调,它将被'read()'操作触发,并且可能会做某些事情(比如放弃它)。 –