在Netty 4中,ctx.close和ctx.channel.close有什么区别?

时间:2014-01-20 17:59:24

标签: netty

有什么区别吗? ctx.close只是ctx.channel.close的缩短版本吗?

2 个答案:

答案 0 :(得分:26)

我们假设我们在管道中有三个处理程序,它们都拦截close()操作,并在其中调用ctx.close()

ChannelPipeline p = ...;
p.addLast("A", new SomeHandler());
p.addLast("B", new SomeHandler());
p.addLast("C", new SomeHandler());
...

public class SomeHandler extends ChannelOutboundHandlerAdapter {
    @Override
    public void close(ChannelHandlerContext ctx, ChannelPromise promise) {
        ctx.close(promise);
    }
}
  • Channel.close()会触发C.close()B.close()A.close(),然后关闭频道。
  • ChannelPipeline.context("C").close()会触发B.close()A.close(),然后关闭频道。
  • ChannelPipeline.context("B").close()会触发A.close(),然后关闭频道。
  • ChannelPipeline.context("A").close()将关闭频道。不会召唤任何处理程序。

那么,何时应该使用Channel.close()ChannelHandlerContext.close()?经验法则是:

  • 如果您正在编写ChannelHandler并希望关闭处理程序中的频道,请致电ctx.close()
  • 如果要从处理程序外部关闭通道(例如,您有一个不是I / O线程的后台线程,并且您想要关闭该线程的连接。)

答案 1 :(得分:23)

ctx.close()从ChannelHandlerContext开始流经ChannelPipeline,而ctx.channel()。close()将始终从ChannelPipeline的尾部开始。

相关问题