wxr
2024-12-02 ea0b1e8e5f43c5fd0a7d479e25ede3b8cbea464a
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
 
using System;
using System.Text;
/**
* Created by Tong on 2021/9/22.
* link协议粘包拆包
*/
public class LinkMessageDecoder
{
 
    //instance
    private static LinkMessageDecoder instance = new LinkMessageDecoder();
 
    //getInstance
    public static LinkMessageDecoder getInstance()
    {
        return instance;
    }
 
    /**
     * 接收数据缓冲区
     */
    private byte[] byteBuffer;
    private int position;
 
    private byte[] head = System.Text.Encoding.UTF8.GetBytes("Topic:");
 
    public LinkMessageDecoder()
    {
        byteBuffer = new byte[1024 * 20];//100K
    }
 
    /// <summary>
    /// 获取内容长度
    /// </summary>
    /// <param name="topMsgs"></param>
    /// <returns></returns>
    private int getLenght(string[] topMsgs)
    {
        try
        {
            for (int i = 0; i < topMsgs.Length; i++)
            {
                string topMsg = topMsgs[i].Trim();
                if (topMsg.StartsWith("Length:"))
                {
                    return int.Parse(topMsg.Replace("Length:", "").Trim());
                }
            }
        }
        catch (Exception e)
        {
            //LogUtils.e("异常数据:" + topMsgs[0] + "\r\n" + topMsgs[1]);
            return -1;
        }
        //找不到长度
        return -1;
    }
 
    /// <summary>
    /// 获取主题
    /// </summary>
    /// <param name="topMsgs"></param>
    /// <returns></returns>
    private string getTopic(string[] topMsgs)
    {
        for (int i = 0; i < topMsgs.Length; i++)
        {
            string topMsg = topMsgs[i].Trim();
            if (topMsg.StartsWith("Topic:"))
            {
                return topMsg.Replace("Topic:", "");
            }
        }
        //找不到主题
        return null;
    }
 
    /**
     * 获取数据的开始位置
     *
     * @return 数据位的开始索引
     */
    private int getBodyIndex()
    {
        byte r = (byte)'\r';
        byte n = (byte)'\n';
        for (int i = 0; i < position; i++)
        {
            //找出数据内容前面的两个换行
            if (3 <= i && byteBuffer[i - 3] == r && byteBuffer[i - 2] == n && byteBuffer[i - 1] == r && byteBuffer[i] == n)
            {
                //剩余的数据
                return i + 1;
            }
        }
        return -1;
    }
 
    /**
     * 获取头部数据
     *
     * @return
     */
    private string getHeader()
    {
        int bodyIndex = getBodyIndex();
        if (bodyIndex < 0)
        {
            //没有找到头部数据
            return null;
        }
        else
        {
            return System.Text.Encoding.UTF8.GetString(byteBuffer, 0, bodyIndex);
        }
    }
 
    /**
     * 获取数据内容
     *
     * @param lenght
     * @return
     */
    private byte[] getBody(int index, int lenght)
    {
        //是否已经获取完整所有的数据
        byte[] bodyBytes = new byte[lenght];
        if (index < 0 || position < index + lenght)
        {
            //当前数据还没有接收完成
            return null;
        }
 
        for (int i = 0; i < bodyBytes.Length; i++)
        {
            bodyBytes[i] = byteBuffer[index + i];
        }
        return bodyBytes;
    }
 
    /**
     * 移除可能存在的无效数据
     */
    private void removeInVoidBytes()
    {
        int index = 0;
        bool isMatch = false;
        for (; index < position - head.Length; index++)
        {
            isMatch = true;
            for (int j = 0, k = 0; j < head.Length; j++, k++)
            {
                if (head[j] != byteBuffer[index + k])
                {
                    isMatch = false;
                    break;
                }
            }
            if (isMatch)
            {
                break;
            }
        }
 
        if (0 < index && isMatch)
        {
            int endIndex = position;
            position = 0;
            //byteBuffer.clear();
            for (int i = index; i < endIndex; i++)
            {
                byteBuffer[position++] = byteBuffer[i];
            }
        }
    }
 
    /**
     * 移除到指定位置前面的数据
     *
     * @param position 指定位置
     */
    private void remove(int index)
    {
        int endIndex = position;
        position = 0;
        //byteBuffer.clear();
        for (int i = index; i < endIndex; i++)
        {
            byteBuffer[position++] = byteBuffer[i];
        }
    }
 
    public void Decoder(byte[] bytes, Action<string, byte[]> action)
    {
        lock (instance)
        {
            try
            {
                if (null == bytes)
                {
                    return;
                }
 
                System.Array.Copy(bytes, 0, byteBuffer, position, bytes.Length);
                position += bytes.Length;
 
                //如果多条命令打包在一条数据中,都需要处理完
                while (true)
                {
                    removeInVoidBytes();//移除可能存在的无效数据
 
                    //头部数据
                    string header = getHeader();
 
                    if (header == null)
                    {
                        break;
                    }
                    string[] topMsgs = header.Split("\r\n");
 
                    string topic = getTopic(topMsgs);
                    int lenght = getLenght(topMsgs);
                    if (topic == null || lenght <= 0)
                    {
                        //获取不到主题或者头部数据还没有接收完成
                        break;
                    }
 
                    int bodyIndex = getBodyIndex();
                    //是否已经获取完整所有的数据
                    byte[] body = getBody(bodyIndex, lenght);
 
                    if (body == null)
                    {
                        //当前数据还没有接收完成
                        break;
                    }
 
                    remove(bodyIndex + lenght);
 
                    action?.Invoke(topic, body);
 
                }
            }
            catch (Exception ee)
            {
 
            }
        }
    }
}