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

Ngo*_*Dao 15 netty

有什么区别吗?是否ctx.close只是一个较短的版本ctx.channel.close

tru*_*tin 27

假设我们在管道中有三个处理程序,它们都拦截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);
    }
}
Run Code Online (Sandbox Code Playgroud)
  • 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线程的后台线程,并且您想要关闭该线程的连接.)

  • 一般来说,当您知道 ChannelPipeline 中的“稍后”ChannelHandler 不关心关闭事件时,您可以使用 ctx.close() 。 (2认同)

Nor*_*rer 26

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