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

时间:2017-08-15 21:54:00

标签: java netty

Netty的流水线(即 private void sendBlock( service serv, String tic, Resource block, Update update, Info info, ResourceResolver resolver ) throws IOException { private Boolean _alreadyExecuted = Boolean.FALSE; if( tic != null ) { String tic = null; if(!_alreadyExecuted){ getLogger().info("Before startSubmission. Currently _alreadyexecuted is " +_alreadyExecuted); serv.getService().start( tic, info ); getLogger().info("After startSubmission, _alreadyexecuted is about to change to true. Currently _alreadyexecuted is " +_alreadyExecuted); _alreadyExecuted = Boolean.TRUE; getLogger().info("After startSubmission, _alreadyexecuted has been changed to true. Currently _alreadyexecuted is " +_alreadyExecuted); } } } vs ctx.foo())之前已在StackOverflow上解释过两次:

  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?
  3. 但是,我不理解Netty关于何时使用不同方法的例子的直觉:

    ctx.channel.foo()

    View source on GitHub

    为什么在代理impl的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(); } } }); } 处理程序中使用'from this handler down'样式read,但在channelActive中使用'from the top'样式read }?

1 个答案:

答案 0 :(得分:1)

使用ChannelHandlerContext.read()时,它会从ChannelPipeline所在的ChannelHandler点开始。当您使用Channel.read()时,它将从ChannelPipeline的尾部开始,因此需要在更糟糕的演员阵容中遍历整个ChannelPipeline

此示例使用ctx.read()中的channelActive(...)channel.read()中使用ChannelFutureListener的原因是因为ChannelFutureListener不属于ChannelHandler所以它需要从ChannelPipeline的尾部开始。另请注意,此处Channel不同。