【问题标题】:In Netty 4, what's the difference between ctx.close and ctx.channel.close?在 Netty 4 中,ctx.close 和 ctx.channel.close 有什么区别?
【发布时间】:2014-02-10 00:50:11
【问题描述】:

有什么不同吗? ctx.close 只是 ctx.channel.close 的较短版本吗?

【问题讨论】:

    标签: netty


    【解决方案1】:

    假设我们在管道中有三个处理程序,它们都拦截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 线程的后台线程,并且您想关闭来自该线程的连接。)

    【讨论】:

    • 一般情况下应该用ctx.channel.close吧?你能举出应该使用 ctx.close 的例子吗?
    • 一般来说,当你知道 ChannelPipeline 中的“稍后”ChannelHandler 不关心关闭事件时,你可以使用 ctx.close()。
    • ChannelInboundHandlerAdapter 没有 close() 方法,所以我们不能 @Override 并且项目符号对我来说没有意义。 @trustin 我错过了什么吗?谢谢
    • @Aaron 感谢您的报告。应该是ChannelOutboundHandlerAdapter
    【解决方案2】:

    ctx.close()从ChannelHandlerContext的点开始流过ChannelPipeline,而ctx.channel().close()一直从ChannelPipeline的尾部开始。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-23
      • 1970-01-01
      • 2022-01-19
      • 1970-01-01
      • 1970-01-01
      • 2020-01-01
      • 2022-11-22
      相关资源
      最近更新 更多