2017-08-15 58 views
0

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

回答

1

使用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()'操作觸發,並且可能會做某些事情(比如放棄它)。 –