在使用Netty进行网络编程的时候,通常需要在网络连接的不同阶段进行相应的操作,比如在连接建立时,客户端向服务端发起认证,在接收到数据时对数据内容进行解析等等。那么,连接的不同阶段在netty中如何表示呢? 这便是本文讨论的内容,Netty中ChannelHandller的生命周期。
首先我们先分析小网络连接的生命周期,连接建立 ---> 数据交互 ---> 连接断开,在数据交互阶段,包括从连接中读取数据和向连接中写入数据。知道了连接的生命周期,就可以按图索骥的在各个阶段进行想要的操作。而在Netty中,网络连接的不同生命周期都可以通过回调的方式来绑定相应的逻辑,这个回调接口就是ChannelHandler
,这里主要我们以ChannelInboundHandler
为例进行分析。在ChannelInboundHandler
中定义了如下和生命周期相关的接口:
加上在父类``中定义的两个:
这些回调接口的调用书序是什么呢?我们通过写一个LifeCycleHandler
来看下ChannelInboundHandler的生命周期的顺序。
public class LifeCycleInBoundHandler extends ChannelInboundHandlerAdapter { @Override public void channelRegistered(ChannelHandlerContext ctx) throws Exception { out.println("channelRegistered: channel注册到NioEventLoop"); super.channelRegistered(ctx); } @Override public void channelUnregistered(ChannelHandlerContext ctx) throws Exception { out.println("channelUnregistered: channel取消和NioEventLoop的绑定"); super.channelUnregistered(ctx); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { out.println("channelActive: channel准备就绪"); super.channelActive(ctx); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { out.println("channelInactive: channel被关闭"); super.channelInactive(ctx); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { out.println("channelRead: channel中有可读的数据" ); super.channelRead(ctx, msg); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { out.println("channelReadComplete: channel读数据完成"); super.channelReadComplete(ctx); } @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { out.println("handlerAdded: handler被添加到channel的pipeline"); super.handlerAdded(ctx); } @Override public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { out.println("handlerRemoved: handler从channel的pipeline中移除"); super.handlerRemoved(ctx); }}
启动服务器和Client,连接成功后,断开client的连接,Server端输出结果如下:
handlerAdded: handler被添加到channel的pipelinechannelRegistered: channel注册到NioEventLoopchannelActive: channel准备就绪channelRead: channel中有可读的数据channelReadComplete: channel读数据完成channelReadComplete: channel读数据完成channelInactive: channel被关闭channelUnregistered: channel取消和NioEventLoop的绑定handlerRemoved: handler从channel的pipeline中移除
从上面结果可以知道,从连接建立到连接断开,handler的生命周期回调接口调用顺序如下:
handlerAdded -> channelRegistered -> channelActive -> channelRead -> channelReadComplete-> channelInactive -> channelUnRegistered -> handlerRemoved
下面具体说下每个回调的具体含义: