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(); } }