1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
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");
 
    }
}