package com.anyun.im_lib.netty; import android.util.Log; import com.anyun.im_lib.interf.IMSClientInteface; import com.anyun.im_lib.util.ByteUtil; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; /** * MyApplication2 * 消息接收处理handler * Created by lzw on 2019/12/4. 10:58:43 * 邮箱:632393724@qq.com * All Rights Saved! Chongqing AnYun Tech co. LTD */ public class TCPReadHandler extends ChannelInboundHandlerAdapter { private static final String TAG = TCPReadHandler.class.getSimpleName(); private IMSClientInteface imsClient; public TCPReadHandler(IMSClientInteface imsClient) { this.imsClient = imsClient; } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { super.channelActive(ctx); Log.i(TAG, "channelInactive"); Channel channel = ctx.channel(); if (channel != null){ channel.close(); ctx.close(); } //触发重连 imsClient.resetConnect(false); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { super.exceptionCaught(ctx, cause); Log.i(TAG, "exceptionCaught: "+cause.getMessage()); Channel channel = ctx.channel(); if (channel != null){ channel.close(); ctx.close(); } //触发重连 imsClient.resetConnect(false); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // TODO: 2019/12/4 //服务端返回消息后 ByteBuf buf = (ByteBuf) msg; int len = buf.readableBytes(); if (len>0){ byte[] req = new byte[len+2]; buf.readBytes(req,1,len); req[0] = 0x7E; req[len+1] = 0x7e; Log.i(TAG, "channelRead hex str: "+ ByteUtil.byte2HexStr(req)); if (req!=null && req.length>0){ imsClient.getMsgDispatcher().receivedMsg( req ); } } } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { super.channelReadComplete(ctx); Log.i(TAG, "channelReadComplete"); } }