NettyHandler 常用生命周期方法

NettyHandler 常用生命周期方法

@Component
@ChannelHandler.Sharable  //表示这里是线程安全的
public class ImServerHandler extends ChannelInboundHandlerAdapter {


    private static final Logger logger = LoggerFactory.getLogger(this.getClass());
 
    /**
     * 一旦连接,第一个执行,表示连接建立,一般心跳会在这里面发送
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception { 
        logger.info("[客户端] 上线 {} localAddress => {} remoteAddress => {}", ctx.channel().hashCode(), ctx.channel().localAddress(), ctx.channel().remoteAddress());
        //发送心跳包
    }


    /**
     * 绑定完成,一般在这方法内,做一些登录操作
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {         
        logger.info("全部绑定到线程上,已经是一个完整的逻辑处理链时,会回调此方法:local {} remote {} => {}", ctx.channel().localAddress(), ctx.channel().remoteAddress(), msg);  
        //发送登录消息
    }


    /**
     * 读取消息
     *
     * @param ctx
     * @param obj
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object obj) throws Exception {
        logger.info("收到客户端发过来的消息:local {} remote {} => {}", ctx.channel().localAddress(), ctx.channel().remoteAddress(), msg);  
        //收到发送来的消息,对 obj 进行解析处理
    }


    /**
     * 数据读取完毕
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        logger.info("[客户端] 数据读取完成 " + ctx.hashCode() + " => " + ctx.channel().remoteAddress());
        ctx.flush(); //读完后,刷新通道
    }


    /**
     * 表示不活动状态,XX 离线了-- channelInactive > handlerRemoved
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.info("[客户端] 离线 localAddress => {} remoteAddress => {}", ctx.channel().localAddress(), ctx.channel().remoteAddress());
        //这边在离线时,处理其它逻辑,比如从注册中心中移除注册
    }


    /**
     * 断开连接被触发--将XX客户下线信息,推送当前在线的客户
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { 
        logger.info("[客户端] 下线  localAddress => {} remoteAddress => {}", ctx.channel().localAddress(), ctx.channel().remoteAddress()); 
        //基本不用        
    }



    /**
     * 处理异常, 一般是需要关闭通道
     *
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //出现异常的时候,执行相关操作并关闭通道
        cause.printStackTrace(); //有离线的时候,会触发,这里需要对通道进行关闭,日志可以不打印
        ctx.close();
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章