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

标签 netty

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

最佳答案

假设我们在管道中有三个处理程序,它们都拦截 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() ,然后关闭 channel 。
  • ChannelPipeline.context("C").close()将触发B.close() , A.close() ,然后关闭 channel 。
  • ChannelPipeline.context("B").close()将触发A.close() ,然后关闭 channel 。
  • ChannelPipeline.context("A").close()将关闭 channel 。不会调用任何处理程序。

  • 所以,什么时候应该使用 Channel.close()ChannelHandlerContext.close() ?经验法则是:
  • 如果您正在编写 ChannelHandler如果想关闭处理程序中的 channel ,请调用 ctx.close() .
  • 如果您从处理程序外部关闭 channel (例如,您有一个不是 I/O 线程的后台线程,并且您想关闭来自该线程的连接。)
  • 关于netty - 在 Netty 4 中,ctx.close 和 ctx.channel.close 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21240981/

    相关文章:

    java - 使用netty高速发送消息时出现OOM异常

    java - Azure 和 Apache Mina

    html - 使用 Netty HTTP2 实现支持服务器发送事件

    java - LibGDX - HTML5 runner,带网络?

    java - netty echo 服务器发送消息,但我没有看到它

    java - 理解 Netty 对线程的使用

    netty - 向 netty telnet 示例添加身份验证

    java - 使用 Apache HttpClient 将数据发布到 netty

    java - 如何在java中存储unsigned short?

    java - Netty channel 处理程序、线程和堆栈