使用Netty中的例子ctx.read()与ctx.channel.read()
问题描述:
Netty中的流水线(即ctx.foo()
VS ctx.channel.foo()
)已经在计算器上过两次解释说:使用Netty中的例子ctx.read()与ctx.channel.read()
- Any difference between ctx.write() and ctx.channel().write() in netty?
- 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();
}
}
});
}
为什么要用“从该处理程序下”在channelActive
处理代理IMPL的风格read
,但使用“从顶部”的风格read
在channelRead
?
答
使用ChannelHandlerContext.read()
时,它将从ChannelPipeline
中的ChannelHandler
所在的点开始。当您使用Channel.read()
时,它将从ChannelPipeline
的尾部开始,因此需要遍布整个ChannelPipeline
,投下较差的阵容。
之所以出现这种例子在ChannelFutureListener
使用ctx.read()
在channelActive(...)
但channel.read()
是因为ChannelFutureListener
不是ChannelHandler
的一部分,所以它需要在ChannelPipeline
的尾部开始。另外请注意,这里的Channel
不一样。
我还没有完全理解这一点。当你说“它将从处理程序所在的管道中的点开始”时,后续处理程序正在调用什么。 AFAIK当你调用'.read()'时,你所要做的就是要求套接字读取一些数据......然后如果/当数据到达时,'channelRead'将在流水线的_start_处被触发。或者当你调用'ctx.read()'时,如果/当数据到达时,前面的处理程序是否没有收到任何数据? –
如果你在'ChannelPipeline'中有'ChannelOutboundHandler',它们有'read(...)'回调,它将被'read()'操作触发,并且可能会做某些事情(比如放弃它)。 –