schangxiang@126.com
2025-11-04 ca398287db3f5ea01f03aac4a85edb13b28100a6
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
 
using Sodao.FastSocket.Server;
using Sodao.FastSocket.Server.Messaging;
using Sodao.FastSocket.SocketBase;
using HxCommonLib.Log;
 
 
 
namespace HxSocket
{
    /// <summary>
    /// 服务端程序监听类:与客户端建立连接,同时接收客户端消息,发送消息到客户端。
    /// 接收消息是一个线程
    /// 监听客户端连接是一个线程
    /// </summary>
    public class SocketTcpListener
    {
        private bool            m_bThreadRecvRunBreak = false;                     //接收线程中断
        private bool            m_bThreadConnRunBreak = false;                     //连接线程中断
        private TcpListener     m_tcpServerListener = null;
        private TcpClient       m_tcpClient = null;
        private NetworkStream   m_tcpRecvStream = null;
        private NetworkStream   m_tcpSendStream = null;
        public string           m_strRecvMessage = null;                        //接收到消息内容
        public bool             m_bRecvMessage = false;                         //是否接收到消息
        public bool             m_bConnectedClient = false;                     //已经连接到客户端
        public List<string>     m_listRecvMessage = new List<string>();         //缓存所有的消息队列,同时可以收到多条消息
        public string           m_strDevicesConntectedStatus = "";              //设备连接状态,心跳包
        /// <summary>
        /// //用于锁定m_listRecvMessage
        /// </summary>                       
        public object m_objListLock = new object();   
 
        public SocketTcpListener()
        {
            m_bConnectedClient = false;
        }
 
        /// <summary>
        /// 接收消息线程
        /// </summary>
        void RecvThreadMethod()
        {
            try
            {
                byte[] data = new byte[1024];
                //[1]TcpListener对Socket进行了封装,这各类会自己创建Socket对象,服务端端口为2018
                m_tcpServerListener = new TcpListener(IPAddress.Any, 2018);
                //[2]开始进行监听
                m_tcpServerListener.Start();
 
                //[3]等待客户端连接过来
                m_tcpClient = m_tcpServerListener.AcceptTcpClient();
 
                if (m_tcpClient != null)
                {
                    LogConstant.logger.Print("客户端已连接:" + m_tcpClient.Client.RemoteEndPoint.ToString());
                    m_bConnectedClient = true;
                    //[4]取得从客户端发来的数据
                    m_tcpRecvStream = m_tcpClient.GetStream(); //这是一个网络流,从这个网络流可以去的从客户端发来的数据
                }
 
                while (!m_bThreadRecvRunBreak)
                {
                    /* * 0表示从数组的哪个索引开始读取数据 * 1024 表示最大的读取数 * */
                    try
                    {
                        if (m_bConnectedClient)
                        {
                            int length = m_tcpRecvStream.Read(data, 0, 1024);
                            m_strRecvMessage = Encoding.UTF8.GetString(data, 0, length);
                            AddMessageToList();
                        }
                        else
                        {
                            Thread.Sleep(500);
                        }
                    }
                    catch (System.Exception ex)
                    {
                        LogConstant.logger.Print("[ERROR] " + ex.ToString());
                    }
                }
            }
            catch (System.Exception ex)
            {
                LogConstant.logger.Print("[ERROR] " + ex.ToString());
            }
        }
 
        void AddMessageToList()
        {
            if (m_strRecvMessage.Length > 0)
            {
                m_bRecvMessage = true;
                int nListRecvMsgCnt = 0;
                string textCommand = m_strRecvMessage;
                string[] asCommand = textCommand.Split(new string[] {"\r\n"}, StringSplitOptions.RemoveEmptyEntries); //防止两条命令合并为一条来接收
                if (asCommand.Length >= 0)
                {
                    lock (m_objListLock)
                    {
                        for (int i = 0; i < asCommand.Length; i++)
                        {
                            if (asCommand[i].Contains("COMMAND"))
                            {
                                if (asCommand[i].Contains("ID0")) //HeartBeat 
                                {
                                    m_strDevicesConntectedStatus = asCommand[i].Substring(asCommand[i].IndexOf("COMMAND") + 7);
                                    continue;
                                }
                                m_listRecvMessage.Add(asCommand[i] + "\r\n");
                            }
                        }
                        nListRecvMsgCnt = m_listRecvMessage.Count;
                    }
                }
 
                LogConstant.logger.Print("接收:" + m_strRecvMessage + "=" + nListRecvMsgCnt);
            } 
        }
 
        
        /// <summary>
        /// 判断客户端是否连接,断开后重新建立连接线程
        /// </summary>
        void ConnectThreadMethod()
        {
            while (!m_bThreadConnRunBreak)
            {
                try
                {
                    if (m_tcpClient != null && m_tcpClient.Connected)
                    {
                        try
                        {
                            int a1 = m_tcpClient.Client.Available;
                            int a2 = m_tcpClient.Available;
                            if (m_tcpClient.Client.Poll(500, SelectMode.SelectRead))
                            {
                                byte[] data = new byte[512];
                                int nRead = m_tcpClient.Client.Receive(data);
                                if (nRead == 0)
                                {
                                    //socket连接已断开
                                    m_bConnectedClient = false;
                                }
                            }
                        }
                        catch (System.Exception ex)
                        {
                            if (m_tcpSendStream != null)
                            {
                                m_tcpSendStream.Close();
                                m_tcpSendStream.Dispose();
                                m_tcpSendStream = null;
                            }
                            if (m_tcpClient != null)
                            {
                                m_tcpClient.Close();
                            }
 
                            m_bConnectedClient = false;
                            LogConstant.logger.Print("[ERROR] " + ex.ToString());
                        }
                    }
 
                    if (m_tcpClient != null && (!m_tcpClient.Connected || !m_tcpClient.Client.Connected || !m_bConnectedClient))
                    {
                        if (m_tcpSendStream != null)
                        {
                            m_tcpSendStream.Close();
                            m_tcpSendStream.Dispose();
                            m_tcpSendStream = null;
                        }
                        if (m_tcpClient != null)
                        {
                            m_tcpClient.Close();
                        }
 
                        m_bConnectedClient = false;
                        LogConstant.logger.Print("客户端已断开:" + m_tcpClient.Connected);
 
                        //[3]等待客户端连接过来
                        m_tcpClient = m_tcpServerListener.AcceptTcpClient();
                        if (m_tcpClient != null && m_tcpClient.Connected)
                        {
                            LogConstant.logger.Print("客户端已连接:" + m_tcpClient.Client.RemoteEndPoint.ToString());
                            
                            m_tcpRecvStream = m_tcpClient.GetStream();//这是一个网络流,从这个网络流可以去的从客户端发来的数据
                            m_bConnectedClient = true;
                        }
                    }
                    Thread.Sleep(1000);
                }
                catch (System.Exception ex)
                {
                    LogConstant.logger.Print("[ERROR] " + ex.ToString());
                    Thread.Sleep(1000);
                }
            }
        }
 
        /// <summary>
        /// 发送消息线程
        /// </summary>
        /// <param name="strMsg"></param>
        public void SendMessage(string strMsg)
        {
            if (m_tcpServerListener == null)
            {
                return;
            }
 
            if (m_tcpSendStream == null && m_tcpClient != null && m_bConnectedClient)
            {
                m_tcpSendStream = m_tcpClient.GetStream();
            }
            if (m_tcpSendStream == null || !m_bConnectedClient)
            {
                return;
            }
 
            try
            {
                lock (m_tcpSendStream)
                {
                    byte[] dataMsg = Encoding.UTF8.GetBytes(strMsg);
                    m_tcpSendStream.Write(dataMsg, 0, dataMsg.Length);
                    LogConstant.logger.Print("发送:" + strMsg);
                }
            }
            catch (System.Exception ex)
            {
                LogConstant.logger.Print("[ERROR] " + ex.ToString());
            }
        }
        
 
        /// <summary>
        /// 线程开始,启动函数
        /// </summary>
        public void SocketStart()
        {
            LogConstant.logger.Print("监听线程开始,监听端口:" + 2018);
 
            try
            {
                Thread aThread = new Thread(new ThreadStart(RecvThreadMethod));
                Thread bThread = new Thread(new ThreadStart(ConnectThreadMethod));
 
                // Try to restart the aborted thread
                aThread.Start();
                bThread.Start();
                
            }
            catch (ThreadStateException ex)
            {
                LogConstant.logger.Print("[ERROR] " + ex.ToString());
            }
        }
 
        /// <summary>
        /// 线程结束
        /// </summary>
        public void SocketClose()
        {
            if (m_tcpSendStream != null)
            {
                m_tcpSendStream.Close();
            }
            if (m_tcpRecvStream != null)
            {
                m_tcpRecvStream.Close();
            }
            m_bThreadConnRunBreak = true;
            m_bThreadRecvRunBreak = true;
            if (m_tcpClient != null)
            {
                m_bThreadConnRunBreak = true;
                Thread.Sleep(700);
                m_tcpClient.Close();
            }
            if (m_tcpServerListener != null)
            {
                m_tcpServerListener.Stop(); //停止监听       
                m_bThreadRecvRunBreak = true;
                Thread.Sleep(700);
            }
        }
 
        
 
        
 
        /// <summary>
        /// 判断是否正常返回RETN,等到接收,30s超时
        /// </summary>
        /// <param name="strReturn"></param>
        /// <returns></returns>
        public bool CheckReturn(string strDevID, string strReturn)
        {
            bool bReturn = false;
            int nTimeOutCount = 0;  //超时计数器
            while (true) 
            {
                lock (m_objListLock)
                {
                    List<int> listIndex = new List<int>();
                    for (int i = 0; i < m_listRecvMessage.Count; i++)
                    {
                        string strRecvMessage = m_listRecvMessage[i];
                        if (strRecvMessage.Contains(strDevID) && 
                            strRecvMessage.Contains(strReturn))
                        {
                            listIndex.Add(i);
                            m_bRecvMessage = false;
                            bReturn = true;
                            break;
                        }
                    }
 
                    //清空已处理的命令,从后往前清空
                    for (int i = listIndex.Count - 1; i >= 0; i--)
                    {
                        m_listRecvMessage.RemoveAt(listIndex[i]);
                    }
                }
                if (bReturn)
                {
                    break;
                }
 
                Thread.Sleep(10);
                nTimeOutCount++;
                if (nTimeOutCount > 500) //30s超时
                {
                    break;
                }
            }
 
            return bReturn;
        }
 
        /// <summary>
        /// 判断是否正常返回COMMANDDone
        /// </summary>
        /// <param name="strReturn"></param>
        /// <returns></returns>
        public int CheckReturn(string strDevID)
        {
            int nRetCount = 0;
            lock (m_objListLock)
            {
                List<int> listIndex = new List<int>();
                for (int i = 0; i < m_listRecvMessage.Count; i++)
                {
                    string strRecvMessage = m_listRecvMessage[i];
                    if (strRecvMessage.Contains(strDevID) && 
                        strRecvMessage.Contains("COMMANDDone"))
                    {
                        listIndex.Add(i);
                        m_bRecvMessage = false;
                        nRetCount++;
                    }
                }
 
                //清空已处理的命令,从后往前清空
                for (int i = listIndex.Count - 1; i >= 0; i--)
                {
                    m_listRecvMessage.RemoveAt(listIndex[i]);
                }
            }
 
            return nRetCount;
        }
 
       
    }
 
 
    /// <summary>
    /// 汇像socket通信类
    /// </summary>
    public class HxSocketServerService : AbsSocketService<CommandLineMessage>
    {
        /// <summary>
        /// //主控连接句柄
        /// </summary>
        private static IConnection m_mainConnection = null;  
 
        /// <summary>
        /// //用于锁定m_listCacheMessage
        /// </summary>                       
        public static object m_objCacheLock = new object();   
          
        /// <summary>
        /// //缓存所有的消息队列,同时可以收到多条消息
        /// </summary>      
        public static List<string> m_listCacheMessage = new List<string>();   
 
        /// <summary>
        /// //设备连接状态,心跳包
        /// </summary>
        public static string       m_strDevicesConntectedStatus = "";                        
 
 
 
        /// <summary>
        /// 获取通信连接状态
        /// </summary>
        /// <returns></returns>
        public static bool GetConnectedStatus()
        {
            if (m_mainConnection != null && m_mainConnection.Active)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
 
 
        /// <summary>
        /// 连接函数
        /// </summary>
        /// <param name="connection"></param>
        public override void OnConnected(IConnection connection)
        {
            if (m_mainConnection == null)
            {
                base.OnConnected(connection);
                LogConstant.logger.Print("已连上客户端: " + connection.RemoteEndPoint.ToString() + " " + connection.ConnectionID.ToString());
 
                connection.BeginReceive();
 
                m_mainConnection = connection;
            }
            else
            {
                m_mainConnection.BeginDisconnect();
                while (m_mainConnection.Active)
                {
                    Thread.Sleep(200);
                }
                m_mainConnection = null;
            }
        }
 
 
        /// <summary>
        /// 接收函数
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="message"></param>
        public override void OnReceived(IConnection connection, CommandLineMessage message)
        {
            try
            {
                base.OnReceived(connection, message);
                switch (message.CmdName)
                {
                    case "echo":
                        message.Reply(connection, "echo_reply " + message.Parameters[0]);
                        break;
                    case "init":
                        LogConstant.logger.Print("connection:" + connection.ConnectionID.ToString() + " init");
                        message.Reply(connection, "init_reply ok");
                        break;
                    case "RunCommand":
                        if (message.Parameters != null && message.Parameters.Length > 0)
                        {
                            string strContent = String.Join(" ", message.Parameters) + Environment.NewLine;
                            AddMessageToList(strContent);
                            LogConstant.logger.Print("接收:" + strContent);
                        }
                        break;
                    default:
                        AddMessageToList(message.CmdName);
                        LogConstant.logger.Print("接收未知消息:" + message.CmdName);
                        break;
                }
            }
            catch (System.Exception ex)
            {
                LogConstant.logger.Print("[ERROR] " + ex.ToString());
            }
        }
 
 
        /// <summary>
        /// 断连函数
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="ex"></param>
        public override void OnDisconnected(IConnection connection, Exception ex)
        {
            base.OnDisconnected(connection, ex);
            m_mainConnection = null;
            LogConstant.logger.Print(connection.RemoteEndPoint.ToString() + " disconnected");
        }
 
 
        /// <summary>
        /// 异常函数
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="ex"></param>
        public override void OnException(IConnection connection, Exception ex)
        {
            base.OnException(connection, ex);
            LogConstant.logger.Print("[ERROR] " + ex.ToString());
        }
 
 
        /// <summary>
        /// ToPacket see cref="SocketBase.Packet"
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException">value is null</exception>
        public static Packet ToPacket(string value)
        {
            if (value == null) throw new ArgumentNullException("value");
            return new Packet(Encoding.UTF8.GetBytes(string.Concat(value, Environment.NewLine)));
        }
 
 
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="message"></param>
        public static void SendMessage(string message)
        {
            if (m_mainConnection != null && m_mainConnection.Active)
            {
                m_mainConnection.BeginSend(ToPacket(message));
            }
        }
 
 
        /// <summary>
        /// 添加消息到缓存队列
        /// </summary>
        /// <param name="strRecvMessage"></param>
        private void AddMessageToList(string strRecvMessage)
        {
            if (strRecvMessage.Length > 0)
            {
                int nListRecvMsgCnt = 0;
                //防止两条命令合并为一条来接收
                string[] astrCommand = strRecvMessage.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); 
                if (astrCommand.Length >= 0)
                {
                    lock (m_objCacheLock)
                    {
                        for (int i = 0; i < astrCommand.Length; i++)
                        {
                            if (astrCommand[i].Contains("ID0") &&
                                astrCommand[i].Contains("COMMAND")) //HeartBeat 
                            {
                                m_strDevicesConntectedStatus = astrCommand[i].Substring(astrCommand[i].IndexOf("COMMAND") + 7);
                                continue;
                            }
                            if (astrCommand[i].Contains("COMMAND"))
                            {
                                m_listCacheMessage.Add(astrCommand[i] + "\r\n");
                            }
                        }
                        nListRecvMsgCnt = m_listCacheMessage.Count;
                    }
                }
 
                LogConstant.logger.Print("ListRecvMsgCnt = " + nListRecvMsgCnt + "MsgLength = " + strRecvMessage.Length);
            }
        }
 
 
        /// <summary>
        /// 判断是否正常返回RETN,等到接收,30s超时
        /// </summary>
        /// <param name="strDevID">设备ID</param>
        /// <param name="strReturn">返回的指令内容</param>
        /// <returns>是否正常返回Retn指令</returns>
        public static bool CheckReturn(string strDevID, string strReturn)
        {
            bool bReturn = false;
            int nTimeOutCount = 0;  //超时计数器
            while (true)
            {
                lock (m_objCacheLock)
                {
                    List<int> listIndex = new List<int>();
                    for (int i = 0; i < m_listCacheMessage.Count; i++)
                    {
                        string strRecvMessage = m_listCacheMessage[i];
                        if (strRecvMessage.Contains(strDevID) &&
                            strRecvMessage.Contains(strReturn))
                        {
                            listIndex.Add(i);
                            bReturn = true;
                            break;
                        }
                    }
 
                    //清空已处理的命令,从后往前清空
                    for (int i = listIndex.Count - 1; i >= 0; i--)
                    {
                        m_listCacheMessage.RemoveAt(listIndex[i]);
                    }
                }
                if (bReturn)
                {
                    break;
                }
 
                Thread.Sleep(10);
                nTimeOutCount++;
                if (nTimeOutCount > 500) //30s超时
                {
                    break;
                }
            }
 
            return bReturn;
        }
 
 
        /// <summary>
        /// 判断是否正常返回RETN,等到接收,30s超时
        /// </summary>
        /// <param name="strDevID">设备ID</param>
        /// <param name="strRetnCmd">返回的指令内容</param>
        /// <param name="nTimeout">超时时间 ms</param>
        /// <returns>是否正常返回Retn指令</returns>
        public static bool CheckReturn(string strDevID, string strRetnCmd, int nTimeout)
        {
            bool bReturn = false;
            int nTimeOutCount = 0;          //超时计数器
            int nMaxCount = nTimeout / 10;  //最大超时次数
 
            while (true)
            {
                lock (m_objCacheLock)
                {
                    List<int> listIndex = new List<int>();
                    for (int i = 0; i < m_listCacheMessage.Count; i++)
                    {
                        string strRecvMessage = m_listCacheMessage[i];
                        if (strRecvMessage.Contains(strDevID) &&
                            strRecvMessage.Contains(strRetnCmd))
                        {
                            listIndex.Add(i);
                            bReturn = true;
                            break;
                        }
                    }
 
                    //清空已处理的命令,从后往前清空
                    for (int i = listIndex.Count - 1; i >= 0; i--)
                    {
                        m_listCacheMessage.RemoveAt(listIndex[i]);
                    }
                }
 
                if (bReturn)
                {
                    break;
                }
                if (nTimeOutCount++ > nMaxCount) //30s超时
                {
                    break;
                }
                Thread.Sleep(10);
            }
 
            return bReturn;
        }
 
 
        /// <summary>
        /// 判断是否正常返回COMMANDDone
        /// </summary>
        /// <param name="strDevID">设备ID</param>
        /// <returns>判断返回Done指令次数,并从缓存清空</returns>
        public static int CheckDone(string strDevID)
        {
            int nRetCount = 0;
            lock (m_objCacheLock)
            {
                List<int> listIndex = new List<int>();
                for (int i = 0; i < m_listCacheMessage.Count; i++)
                {
                    string strRecvMessage = m_listCacheMessage[i];
                    if (strRecvMessage.Contains(strDevID) &&
                        strRecvMessage.Contains("COMMANDDone"))
                    {
                        listIndex.Add(i);
                        nRetCount++;
                    }
                }
 
                //清空已处理的命令,从后往前清空
                for (int i = listIndex.Count - 1; i >= 0; i--)
                {
                    m_listCacheMessage.RemoveAt(listIndex[i]);
                }
            }
 
            return nRetCount;
        }
 
 
        /// <summary>
        /// 判断是否正常返回COMMANDDone
        /// </summary>
        /// <param name="strDevID">设备ID</param>
        /// <param name="nTimeout">超时时间 ms</param>
        /// <returns>是否成功返回</returns>
        public static bool CheckDone(string strDevID, int nTimeout)
        {
            bool bReturn = false;
            int nTimeOutCount = 0;          //超时计数器
            int nMaxCount = nTimeout / 10;  //最大超时次数
 
            while (true)
            {
                lock (m_objCacheLock)
                {
                    for (int i = 0; i < m_listCacheMessage.Count; i++)
                    {
                        string strRecvMessage = m_listCacheMessage[i];
                        if (strRecvMessage.Contains(strDevID) &&
                            strRecvMessage.Contains("COMMANDDone"))
                        {
                            //清空已处理的命令,从后往前清空
                            m_listCacheMessage.RemoveAt(i);
                            bReturn = true;
                            break;
                        }
                    }
                }
 
                if (bReturn)
                {
                    break;
                }
                if (nTimeOutCount++ > nMaxCount)
                {
                    break;
                }
                Thread.Sleep(10);
            }
 
            return bReturn;
        }
 
 
        /// <summary>
        /// 判断是否正常返回COMMANDDone
        /// </summary>
        /// <param name="strDevID">设备ID</param>
        /// <param name="strCmdNo">命令的唯一编号</param>
        /// <param name="nTimeout">超时时间 ms</param>
        /// <returns>是否成功返回</returns>
        public static bool CheckDone(string strDevID, string strCmdNo, int nTimeout)
        {
            bool bReturn = false;
            int nTimeOutCount = 0;          //超时计数器
            int nMaxCount = nTimeout / 10;  //最大超时次数
 
            while (true)
            {
                lock (m_objCacheLock)
                {
                    for (int i = 0; i < m_listCacheMessage.Count; i++)
                    {
                        string strRecvMessage = m_listCacheMessage[i];
                        if (strRecvMessage.Contains(strDevID) &&
                            strRecvMessage.Contains(strCmdNo) &&
                            strRecvMessage.Contains("COMMANDDone"))
                        {
                            //清空已处理的命令,从后往前清空
                            m_listCacheMessage.RemoveAt(i);
                            bReturn = true;
                            break;
                        }
                    }
                }
 
                if (bReturn)
                {
                    break;
                }
                if (nTimeOutCount++ > nMaxCount) 
                {
                    break;
                }
                Thread.Sleep(10);
            }
 
            return bReturn;
        }
 
 
        /// <summary>
        /// 获取指令返回的字符串
        /// </summary>
        /// <param name="strDevID">设备ID</param>
        /// <param name="strInCmd">发送的请求指令名称如GET0,SET0,ALAM,STOP</param>
        /// <param name="nTimeout">超时时间 ms</param>
        /// <returns>失败返回为空</returns>
        public static string GetReturnValue(string strDevID, string strInCmd, int nTimeout)
        {
            bool bReturn = false;
            string strReturn = "";
            int nTimeOutCount = 0;  //超时计数器
            int nMaxCount = nTimeout / 10;  //最大超时次数
 
            while (true) //等待判断运动到位
            {
                lock (m_objCacheLock)
                {
                    List<int> listIndex = new List<int>();
                    for (int i = 0; i < m_listCacheMessage.Count; i++)
                    {
                        string strRecvMessage = m_listCacheMessage[i];
                        if (strRecvMessage.Contains(strDevID) &&
                            strRecvMessage.Contains(strInCmd))//"GET0"
                        {
                            listIndex.Add(i);
                            strReturn = strRecvMessage.Substring(strRecvMessage.IndexOf(strInCmd));
                            bReturn = true;
                            break;
                        }
                    }
 
                    //清空已处理的命令
                    for (int i = listIndex.Count - 1; i >= 0; i--)
                    {
                        m_listCacheMessage.RemoveAt(listIndex[i]);
                    }
                }
 
                if (bReturn)
                {
                    break;
                }
                if (nTimeOutCount++ > nMaxCount) //超时
                {
                    break;
                }
                System.Threading.Thread.Sleep(10);
            }
 
            return strReturn;
        }
        
        /// <summary>
        /// 是否资源
        /// </summary>
        public static void Release()
        {
            if (m_mainConnection != null)
            {
                m_mainConnection.BeginDisconnect();
                m_mainConnection = null;
            }
            m_listCacheMessage.Clear();
        }
    }
 
    
}