wanshenmean
2026-03-02 bfd4fd8e4a05a681ec10a47992294cf752a764c4
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
using System.Net.Sockets;
using System.Text;
using System.Text.Json;
using System.IO;
 
namespace WIDESEAWCS_Tasks.SocketServer
{
    public partial class TcpSocketServer
    {
        /// <summary>
        /// Òì²½´¦ÀíÓëÒÑÁ¬½ÓµÄTCP¿Í»§¶ËµÄͨÐÅ£¬´¦Àí»úÆ÷ÈËÆðÖØ»ú»á»°ÖеĴ«ÈëÏûÏ¢ºÍ¿Í»§¶Ë״̬¸üС£
        /// </summary>
        /// <remarks>´Ë·½·¨¹ÜÀí¿Í»§¶ËÁ¬½ÓµÄÉúÃüÖÜÆÚ£¬°üÀ¨¶ÁÈ¡ÏûÏ¢¡¢¸üпͻ§¶Ë״̬ºÍµ÷ÓÃÏà¹ØÊ¼þ¡£
        /// µ±´¦Àí½áÊøÊ±£¬¿Í»§¶ËºÍÏà¹ØµÄÍøÂç×ÊÔ´½«±»ÊÍ·Å¡£Èç¹ûÆôÓÃÐÄÌø»ò¿ÕÏг¬Ê±Ñ¡Ï
        /// ½«Ó¦ÓöîÍâµÄÈ¡ÏûÂß¼­¡£Ê¼þµ÷ÓÃÆÚ¼äµÄÒì³£½«±»²¶»ñ²¢ÒÖÖÆ£¬ÒÔÈ·±£»á»°´¦ÀíµÄ³°ôÐÔ¡£</remarks>
        /// <param name="client">±íʾҪ´¦ÀíµÄÔ¶³ÌÁ¬½ÓµÄTCP¿Í»§¶Ë¡£·½·¨Íê³Éºó½«ÊͷŴ˶ÔÏó¡£</param>
        /// <param name="clientId">ÒÑÁ¬½Ó¿Í»§¶ËµÄΨһ±êʶ·û¡£ÓÃÓÚÔÚÕû¸ö»á»°Öиú×ٺ͸üпͻ§¶Ë״̬¡£</param>
        /// <param name="cancellationToken">¿ÉÓÃÓÚÈ¡Ïû¿Í»§¶Ë´¦Àí²Ù×÷µÄÈ¡ÏûÁîÅÆ¡£Èç¹ûÇëÇóÈ¡Ïû£¬·½·¨½«Á¢¼´ÖÕÖ¹´¦Àí¡£</param>
        /// <param name="robotCrane">±íʾÓë¿Í»§¶Ë¹ØÁªµÄ»úÆ÷ÈËÆðÖØ»úµÄµ±Ç°×´Ì¬¶ÔÏó¡£ÓÃÓÚΪÏûÏ¢´¦ÀíºÍʼþµ÷ÓÃÌṩÉÏÏÂÎÄ¡£</param>
        /// <returns>±íʾ´¦Àí¿Í»§¶ËÁ¬½ÓµÄÒì²½²Ù×÷µÄÈÎÎñ¡£µ±¿Í»§¶Ë¶Ï¿ªÁ¬½Ó»òÇëÇóÈ¡ÏûʱÈÎÎñÍê³É¡£</returns>
        public async Task HandleClientAsync(TcpClient client, string clientId, CancellationToken cancellationToken, RobotSocketState robotCrane)
        {
            using (client)
            using (NetworkStream networkStream = client.GetStream())
            using (StreamReader reader = new(networkStream, _textEncoding, false, 1024, true))
            using (StreamWriter writer = new(networkStream, _textEncoding, 1024, true) { AutoFlush = true })
            {
                CancellationTokenSource? localCts = null;
                if (_options.EnableHeartbeat || _options.IdleTimeoutSeconds > 0)
                {
                    localCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
                }
 
                try
                {
                    while (!cancellationToken.IsCancellationRequested && client.Connected)
                    {
                        string? message;
                        try
                        {
                            var ct = localCts?.Token ?? cancellationToken;
                            message = await ReceiveFullMessageAsync(networkStream, _textEncoding, ct);
                            //message = await reader.ReadLineAsync().WaitAsync(ct);
                        }
                        catch (OperationCanceledException)
                        {
                            break;
                        }
 
                        if (message == null)
                        {
                            break;
                        }
 
                        UpdateClientStatus(clientId, message);
 
                        string messageLower = message.ToLowerInvariant();
 
                        if (TryHandleRegister(messageLower, message, clientId, networkStream, cancellationToken))
                        {
                            continue;
                        }
 
                        if (MessageReceived != null)
                        {
                            try
                            {
                                // ÅжÏÊÇ·ñΪ JSON ¸ñʽ
                                bool isJsonFormat = TryParseJsonSilent(message);
                                _ = MessageReceived.Invoke(message, isJsonFormat, client, robotCrane);
                            }
                            catch { }
                        }
                    }
                }
                finally
                {
                    try { localCts?.Cancel(); localCts?.Dispose(); } catch { }
                    RemoveClient(clientId);
                    try { _ = RobotReceived.Invoke(clientId); } catch { }
                }
            }
        }
 
        /// <summary>
        /// ³¢ÊÔ´¦ÀíÀ´×Ô¿Í»§¶ËµÄÉ豸ע²áÇëÇó¡£·µ»ØÒ»¸öֵָʾ¸ÃÏûÏ¢ÊÇ·ñ±»×÷Ϊע²áÇëÇó´¦Àí¡£
        /// </summary>
        /// <remarks>Èç¹ûÏûÏ¢ÊÇÓÐЧµÄ×¢²áÇëÇóÇÒ°üº¬·Ç¿ÕµÄÉ豸±êʶ·û£¬
        /// Ôò½«É豸°ó¶¨µ½¿Í»§¶Ë²¢·¢ËÍÈ·ÈÏÐÅÏ¢¡£´Ë·½·¨²»»áÒòÎÞЧÏûÏ¢¶øÅ׳öÒì³££»
        /// Ëü½ö·µ»Ø false¡£</remarks>
        /// <param name="messageLower">¿Í»§¶ËÏûÏ¢µÄСд°æ±¾£¬ÓÃÓÚÅжÏÏûÏ¢ÊÇ·ñΪע²áÇëÇó¡£</param>
        /// <param name="message">°üº¬×¢²áÃüÁîºÍÉ豸±êʶ·ûµÄԭʼ¿Í»§¶ËÏûÏ¢¡£</param>
        /// <param name="clientId">·¢ËÍ×¢²áÇëÇóµÄ¿Í»§¶ËµÄΨһ±êʶ·û¡£</param>
        /// <param name="client">Óë¿Í»§¶ËͨÐŵÄTCP¿Í»§¶ËÁ¬½Ó¡£</param>
        /// <param name="cancellationToken">¿ÉÓÃÓÚÈ¡Ïû×¢²á²Ù×÷µÄÈ¡ÏûÁîÅÆ¡£</param>
        /// <returns>Èç¹ûÏûÏ¢±»Ê¶±ð²¢×÷Ϊע²áÇëÇó´¦Àí£¬Ôò·µ»Ø true£»·ñÔò·µ»Ø false¡£</returns>
        private bool TryHandleRegister(string messageLower, string message, string clientId, NetworkStream networkStream, CancellationToken cancellationToken)
        {
            if (!messageLower.StartsWith("register,"))
            {
                return false;
            }
 
            string deviceId = message.Substring("register,".Length).Trim();
            if (!string.IsNullOrEmpty(deviceId))
            {
                lock (_syncRoot)
                {
                    _deviceBindings[deviceId] = clientId;
                }
 
                _ = WriteToClientAsync(clientId, networkStream, $"Registered,{deviceId}", cancellationToken);
            }
 
            return true;
        }
 
        /// <summary>
        /// ¸üпͻ§¶Ë״̬
        /// </summary>
        /// <param name="clientId"></param>
        /// <param name="message"></param>
        private void UpdateClientStatus(string clientId, string message)
        {
            lock (_syncRoot)
            {
                _clientLastActive[clientId] = DateTime.Now;
 
                if (!_clientEncodings.ContainsKey(clientId))
                {
                    if (_options.AutoDetectEncoding && _autoDetectedGb2312 != null)
                    {
                        bool isUtf8 = TryParseJsonSilent(message) || IsLikelyUtf8(_textEncoding.GetBytes(message));
                        _clientEncodings[clientId] = isUtf8 ? _textEncoding : _autoDetectedGb2312;
                    }
                    else
                    {
                        _clientEncodings[clientId] = _textEncoding;
                    }
                }
            }
        }
 
        /// <summary>
        /// Ð´ÈëÏûÏ¢µ½¿Í»§¶Ë
        /// </summary>
        /// <param name="clientId"></param>
        /// <param name="networkStream"></param>
        /// <param name="message"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        private async Task WriteToClientAsync(string clientId, NetworkStream networkStream, string message, CancellationToken cancellationToken)
        {
            SemaphoreSlim? sem = null;
            Encoding? enc = null;
            lock (_syncRoot)
            {
                _clientLocks.TryGetValue(clientId, out sem);
                _clientEncodings.TryGetValue(clientId, out enc);
            }
 
            enc ??= _textEncoding;
 
            if (sem != null) await sem.WaitAsync(cancellationToken);
            try
            {
                var framedMessage = BuildFramedMessage(message);
                var data = enc.GetBytes(framedMessage);
                await networkStream.WriteAsync(data, 0, data.Length, cancellationToken);
            }
            finally
            {
                if (sem != null) sem.Release();
            }
        }
 
        /// <summary>
        /// Ìí¼ÓÏûϢ֡ͷβ
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        private string BuildFramedMessage(string message)
        {
            var header = _options.MessageHeader ?? string.Empty;
            var footer = _options.MessageFooter ?? string.Empty;
            return header + (message ?? string.Empty) + footer;
        }
 
        /// <summary>
        /// JSON¸ñʽ³¢ÊÔ½âÎö£¨¾²Ä¬Ê§°Ü£©
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        private static bool TryParseJsonSilent(string message)
        {
            if (string.IsNullOrWhiteSpace(message)) return false;
            char c = message.TrimStart()[0];
            if (c != '{' && c != '[') return false;
            try { JsonDocument.Parse(message); return true; } catch { return false; }
        }
 
        /// <summary>
        /// utf-8 ¿ÉÄÜÐÔ¼ì²â
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        private static bool IsLikelyUtf8(byte[] data)
        {
            int i = 0;
            while (i < data.Length)
            {
                byte b = data[i];
                if (b <= 0x7F) { i++; continue; }
                if (b >= 0xC2 && b <= 0xDF)
                {
                    if (i + 1 >= data.Length) return false;
                    if ((data[i + 1] & 0xC0) != 0x80) return false;
                    i += 2; continue;
                }
                if (b >= 0xE0 && b <= 0xEF)
                {
                    if (i + 2 >= data.Length) return false;
                    if ((data[i + 1] & 0xC0) != 0x80 || (data[i + 2] & 0xC0) != 0x80) return false;
                    i += 3; continue;
                }
                if (b >= 0xF0 && b <= 0xF4)
                {
                    if (i + 3 >= data.Length) return false;
                    if ((data[i + 1] & 0xC0) != 0x80 || (data[i + 2] & 0xC0) != 0x80 || (data[i + 3] & 0xC0) != 0x80) return false;
                    i += 4; continue;
                }
                return false;
            }
            return true;
        }
 
        /// <summary>
        /// ¶ÁÈ¡ÍêÕûÏûÏ¢
        /// </summary>
        /// <param name="networkStream">×Ö½ÚÁ÷</param>
        /// <param name="encoding">±àÂë¸ñʽ</param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        private async Task<string?> ReceiveFullMessageAsync(NetworkStream networkStream, Encoding encoding, CancellationToken cancellationToken)
        {
            var header = _options.MessageHeader ?? string.Empty;
            var footer = _options.MessageFooter ?? string.Empty;
 
            var buffer = new byte[1024];
            var builder = new StringBuilder();
 
            while (true)
            {
                int bytesRead = await networkStream.ReadAsync(buffer.AsMemory(0, buffer.Length), cancellationToken);
                if (bytesRead <= 0)
                {
                    if (builder.Length == 0) return null;
                    return string.IsNullOrEmpty(header) && string.IsNullOrEmpty(footer) ? builder.ToString() : null;
                }
 
                builder.Append(encoding.GetString(buffer, 0, bytesRead));
 
                if (string.IsNullOrEmpty(header) && string.IsNullOrEmpty(footer))
                {
                    if (!networkStream.DataAvailable)
                    {
                        break;
                    }
                    continue;
                }
 
                var data = builder.ToString();
                var headerIndex = string.IsNullOrEmpty(header) ? 0 : data.IndexOf(header, StringComparison.Ordinal);
                if (headerIndex < 0)
                {
                    continue;
                }
 
                var startIndex = headerIndex + header.Length;
                var footerIndex = string.IsNullOrEmpty(footer) ? data.Length : data.IndexOf(footer, startIndex, StringComparison.Ordinal);
                if (footerIndex >= 0)
                {
                    return data.Substring(startIndex, footerIndex - startIndex);
                }
            }
 
            return builder.ToString();
        }
    }
}