Netty ChannelHandler的生命周期

ChannelHandler方法的执行是有顺序的,而这个执行顺序可以被称为ChannelHandler的生命周期。

 

LifeCyCleTestHandler

import io.netty.channel.ChannelInboundHandlerAdapter;

import io.netty.channel.ChannelHandlerContext;

public class LifeCyCleTestHandler extends ChannelInboundHandlerAdapter {

    // handlerAdded():指当检测到新连接之后,调用ch.pipeline().addLast(new LifeCyCleTestHandler());之后的回调,
    // 表示在当前Channel中,已经成功添加了一个Handler处理器。
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        System.out.println("逻辑处理器被添加: handlerAdded()");
        super.handlerAdded(ctx);
    }

    // channelRegistered():这个回调方法表示当前Channel的所有逻辑处理已经和某个NIO线程建立了绑定关系,
    // 接收新的连接,然后创建一个线程来处理这个连接的读写,只不过在Netty里使用了线程池的方式,只需要从线程池里去抓一个线程绑定在这个Channel上即可。
    // 这里的NIO线程通常指NioEventLoop。
    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel绑定到线程(NioEventLoop): channelRegistered()");
        super.channelRegistered(ctx);
    }

    // channelActive():当Channel的所有业务逻辑链准备完毕(即Channel的Pipeline中已经添加完所有的Handler),
    // 以及绑定好一个NIO线程之后,这个连接才真正被激活,接下来就会回调到此方法。
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel准备就绪: channelActive()");
        super.channelActive(ctx);
    }

    // channelRead():客户端向服务端发送数据,每次都会回调此方法,表示有数据可读。
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("channel有数据可读: channelRead()");
        super.channelRead(ctx, msg);
    }

    // channelReadComplete():服务端每读完一次完整的数据,都回调该方法,表示数据读取完毕。
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel某次数据读完: channelReadComplete()");
        super.channelReadComplete(ctx);
    }

    // channelInactive():表面上这个连接已经被关闭了,这个连接在TCP层面已经不再是ESTABLISH状态了。
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel被关闭: channelInactive()");
        super.channelInactive(ctx);
    }

    // channelUnregistered():既然连接已经被关闭,那么与这个连接绑定的线程就不需要对这个连接负责了。这个回调表明与这个连接对应的NIO线程移除了对这个连接的处理。
    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel取消线程(NioEventLoop)的绑定: channelUnregistered()");
        super.channelUnregistered(ctx);
    }

    // handlerRemoved():我们给这个连接添加的所有业务逻辑处理器都被移除。
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.out.println("逻辑处理器被移除: handlerRemoved()");
        super.handlerRemoved(ctx);
    }

}

  

 

posted @ 2024-05-22 11:39  草木物语  阅读(66)  评论(0)    收藏  举报