Netty 中的 channelInactive 和 channe.closeFuture().addListener() 有什么不同
what is the different between channelInactive and channe.closeFuture().addListener() in Netty
public class ChannelActiveHandler extends SimpleChannelInboundHandler {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("channel open");
// add closeListener
ctx.channel().closeFuture().addListener(future->{
// do somthing when channel is close!
System.out.println("channel close! state:"+ctx.channel().isActive());
});
super.channelActive(ctx);
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
// do somthing when channel is close!
System.out.println("channel inactive!");
super.channelInactive(ctx);
}
}
如上,Netty中的channelInactive()
和channel.closeFuture().addListener()
有什么不同。当通道关闭时将调用两种方法。
两种方法能达到同样的效果吗?
在您的用例中,这些没有什么不同。也就是说,在 channelInactive(...)
中,您还可以延迟将事件触发到管道中的下一个处理程序。通常,如果您在处理程序中使用 channelActive
,您还应该根据需要使用其他方法。
public class ChannelActiveHandler extends SimpleChannelInboundHandler {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("channel open");
// add closeListener
ctx.channel().closeFuture().addListener(future->{
// do somthing when channel is close!
System.out.println("channel close! state:"+ctx.channel().isActive());
});
super.channelActive(ctx);
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
// do somthing when channel is close!
System.out.println("channel inactive!");
super.channelInactive(ctx);
}
}
如上,Netty中的channelInactive()
和channel.closeFuture().addListener()
有什么不同。当通道关闭时将调用两种方法。
两种方法能达到同样的效果吗?
在您的用例中,这些没有什么不同。也就是说,在 channelInactive(...)
中,您还可以延迟将事件触发到管道中的下一个处理程序。通常,如果您在处理程序中使用 channelActive
,您还应该根据需要使用其他方法。