schangxiang@126.com
2025-11-04 f5ed29dc26c7cd952d56ec5721a2efc43cd25992
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
using DataEntity.Sockets.Base;
using HxEnum;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using XCommon;
using XCommon.Log;
using XImagingXhandler.XDAL;
using static HxEnum.StateEnum;
 
namespace HxSocketImplement.Sockets
{
    /// <summary>
    /// Socket服务
    /// </summary>
    public class HxSockServiceExecute
    {
        #region 变量  
        /// <summary>
        /// 缓存参数
        /// </summary> 
        public static Dictionary<string, SocketParameterModel> CacheSocketParameterData = new Dictionary<string, SocketParameterModel>();
 
        /// <summary>
        /// 监测心跳Thread
        /// </summary>
        private static Thread checkHeartbeatThread = null;
        /// <summary>
        /// 接收消息Thread
        /// </summary>
        private static Thread getReceiveThread = null;
        #endregion
 
        #region 获取指定设备类型缓存数据
        /// <summary>
        /// 获取指定设备类型缓存数据
        /// </summary>
        /// <param name="equipmentType">类型</param> 
        /// <param name="ip">IP</param>
        /// <param name="port">端口</param>
        /// <param name="equipmentId">设备ID</param>
        /// <returns></returns>
        public static SocketParameterModel GetSocketParameterModel(string equipmentType, string ip, int port, string equipmentId)
        {
            if (!string.IsNullOrWhiteSpace(equipmentType))
            {
                var cacheSocketParameterData = CacheSocketParameterData.Where(x => x.Key == equipmentType + ip + port + equipmentId);
                if (cacheSocketParameterData != null && cacheSocketParameterData.Count() > 0)
                {
                    return cacheSocketParameterData.FirstOrDefault().Value;
                }
            }
            return null;
        }
        #endregion
 
        #region 连接+断开+检查心跳
        #region 连接服务端
        /// <summary>
        /// 连接服务端
        /// </summary>
        /// <param name="equipmentType">类型</param> 
        /// <param name="ip">IP</param>
        /// <param name="port">端口</param>
        /// <param name="equipmentId">设备ID</param>
        /// <returns></returns>
        public static bool Connect(string equipmentType, string ip, int port, string equipmentId)
        {
            var socketParameterModel = GetSocketParameterModel(equipmentType, ip, port, equipmentId);
            try
            {
                if (socketParameterModel != null && socketParameterModel.Socket == null)
                {
                    #region 建立连接
                    bool isConnect = ConnectSocket(socketParameterModel);
                    #endregion
 
                    #region 监测心跳
                    checkHeartbeatThread = new Thread(() => CheckHeartbeat(socketParameterModel));
                    checkHeartbeatThread.IsBackground = true;
                    checkHeartbeatThread.Start();
                    #endregion
 
                    #region 接收消息Thread
                    getReceiveThread = new Thread(() => GetReceive(socketParameterModel));
                    getReceiveThread.IsBackground = true;
                    getReceiveThread.Start();
                    #endregion
 
                    if (isConnect)
                    {
                        LoggerSocketHelper.DebugLog(GetIpInfo(socketParameterModel) + "连接服务器【成功】Connect");
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    if (CheckConnected(socketParameterModel.Socket, socketParameterModel.Ip) == false)
                    {
                        bool isConnect = ConnectSocket(socketParameterModel);
                        if (isConnect)
                        {
                            LoggerSocketHelper.DebugLog(GetIpInfo(socketParameterModel) + "连接服务器【成功】Connect");
                        }
                        else
                        {
                            LoggerSocketHelper.DebugLog(GetIpInfo(socketParameterModel) + "连接服务器【失败】Connect");
                            return false;
                        }
                    }
                    else
                    {
                        LoggerSocketHelper.DebugLog(GetIpInfo(socketParameterModel) + "连接服务器【成功】Connect");
                    }
                }
            }
            catch (Exception ex)
            {
                LoggerSocketHelper.DebugLog(GetIpInfo(socketParameterModel) + "连接服务器【失败】Connect" + ex.Message);
                return false;
            }
            return true;
        }
        #endregion
 
 
        #region 建立连接 
        /// <summary>
        /// 建立连接
        /// </summary>
        /// <param name="socketParameterModel"></param>
        /// <returns></returns>
        public static bool ConnectSocket(SocketParameterModel socketParameterModel)
        {
            try
            {
                #region 建立连接
                socketParameterModel.Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);   //1.0 实例化套接字(IP4寻址地址,流式传输,TCP协议)
                IPAddress address = IPAddress.Parse(socketParameterModel.Ip);   //2.0 创建IP对象
                IPEndPoint endPoint = new IPEndPoint(address, socketParameterModel.Port);   //3.0 创建网络端口包括ip和端口
                socketParameterModel.Socket.Connect(endPoint);   //4.0 建立连接
                #endregion
 
                return true;
            }
            catch (Exception ex)
            {
                LoggerSocketHelper.DebugLog(GetIpInfo(socketParameterModel) + "连接服务器【失败】ConnectSocket" + ex.Message);
            }
            return false;
        }
        #endregion
 
        #region 断开连接
        /// <summary>
        /// 断开连接
        /// </summary>
        /// <param name="equipmentType">类型</param> 
        /// <param name="ip">IP</param>
        /// <param name="port">端口</param>
        /// <param name="equipmentId">设备ID</param>
        /// <returns></returns>
        public static bool BreakConnect(string equipmentType, string ip, int port, string equipmentId)
        {
            var socketParameterModel = GetSocketParameterModel(equipmentType, ip, port, equipmentId);
            if (socketParameterModel != null && socketParameterModel.Socket != null && socketParameterModel.Socket.Connected)
            {
                // 断开与服务端的连接时,监测心跳Thread和接收消息Thread也要关闭
                if (checkHeartbeatThread != null)
                {
                    checkHeartbeatThread.Abort();
                    checkHeartbeatThread = null;
                }
                if (getReceiveThread != null)
                {
                    getReceiveThread.Abort();
                    getReceiveThread = null;
                }
 
                socketParameterModel.Socket.Shutdown(SocketShutdown.Both);
                socketParameterModel.Socket.Close();
                socketParameterModel.Socket.Dispose();
                LoggerSocketHelper.DebugLog(GetIpInfo(socketParameterModel) + "断开连接【成功】BreakConnect");
 
                socketParameterModel.Socket = null;
                socketParameterModel = null;
 
                //Thread.Sleep(500);
                return true;
            }
            else
            {
                LoggerSocketHelper.DebugLog(GetIpInfo(socketParameterModel) + "断开连接【失败】BreakConnect");
            }
            return false;
        }
        #endregion
 
        #region 检查心跳
        /// <summary>
        /// 检查心跳
        /// </summary>
        /// <returns></returns>
        public static bool CheckHeartbeat(SocketParameterModel model)
        {
            while (true)
            {
                try
                {
                    if (CheckConnected(model.Socket, model.Ip))
                    {
                        string msgId = $"{model.Ip}_{model.Port}_{model.EquipmentId}_{model.EquipmentType}_{HxSockServiceExecute.InstrunctionId()}";
                        HeartbeatMoel heartbeatMoel = new HeartbeatMoel
                        {
                            message_id = msgId,//  + "_" + HxSockServiceExecute.InstrunctionId(),
                            message_type = model.HeartMessageType,
                            equipment_id = model.HeartEquipmentId,
                            workflow_id = "workflow_id_" + msgId,
                            equipment_status = 1,
                            actual_device_status = 1,
                            connected = 1,
                            timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                        };
 
                        string sendJson = JsonConvert.SerializeObject(heartbeatMoel) + model.SpecifiedDisplay;
                        byte[] buffer = new byte[2048];
                        buffer = Encoding.UTF8.GetBytes(sendJson);
                        int receive = model.Socket.Send(buffer);
                    }
                    else
                    {
                        #region 建立连接
                        model.Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);   //1.0 实例化套接字(IP4寻址地址,流式传输,TCP协议)
                        IPAddress address = IPAddress.Parse(model.Ip);   //2.0 创建IP对象
                        IPEndPoint endPoint = new IPEndPoint(address, model.Port);   //3.0 创建网络端口包括ip和端口
                        model.Socket.Connect(endPoint);   //4.0 建立连接
                        #endregion
                    }
                }
                catch (Exception ex)
                {
                    LoggerSocketHelper.DebugLog(GetIpInfo(model) + "检查心跳【错误】CheckHeartbeat" + ex.Message);
                }
                Thread.Sleep(5000);
            }
        }
        #endregion
        #endregion
 
        #region 判断SOCKET是否连接
        #region 检查连接是否断开
        /// <summary>
        /// 检查连接是否断开
        /// </summary>
        /// <returns></returns>
        public static bool CheckConnected(Socket socket, string ip)
        {
            if (socket != null && socket.Connected && PingOC(ip) && ComUtility.IsSocketConnected(socket))
            {
                return true;
            }
            return false;
        }
        #endregion
 
        #region 检查一个Socket是否可连接(PING网络是否通)
        /// <summary>
        /// 检查一个Socket是否可连接(PING网络是否通)
        /// </summary>
        /// <param name="ips"></param>
        /// <returns></returns>
        public static bool PingOC(String ips)
        {
            return true;
 
            //bool ret;
            //Process p = new Process();
            //p.StartInfo.FileName = "cmd.exe";
            //p.StartInfo.UseShellExecute = false;
            //p.StartInfo.RedirectStandardInput = true;
            //p.StartInfo.RedirectStandardOutput = true;
            //p.StartInfo.RedirectStandardError = true;
            //p.StartInfo.CreateNoWindow = true;
            //int i = 0;
            //p.Start();
            //p.StandardInput.WriteLine("ping -n 1 " + ips);
            //p.StandardInput.WriteLine("exit");
            //string strRst = p.StandardOutput.ReadToEnd();
            //if (strRst.IndexOf("(100%") == -1)
            //{
            //    ret = true;
            //}
            //else
            //{
            //    ret = false;
            //}
            //p.Close();
            //return ret;
        }
        #endregion
        #endregion
 
        #region 发送和接收数据
        #region 发送数据
        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="equipmentType">设备类别</param>
        /// <param name="ip">IP</param>
        /// <param name="port">端口</param>
        /// <param name="equipmentId">设备ID</param>
        /// <param name="data">JSON参数据</param>
        /// <param name="workflow_id">工作流ID</param>
        /// <returns></returns>
        public static Result SendData(string equipmentType, string ip, int port, string equipmentId, string data, string workflow_id)
        {
            Result result = new Result();
            var socketParameterModel = GetSocketParameterModel(equipmentType, ip, port, equipmentId);
            if (socketParameterModel != null)
            {
                if (CheckConnected(socketParameterModel.Socket, socketParameterModel.Ip))
                {
                    bool blockingState = socketParameterModel.Socket.Blocking;
                    try
                    {
                        #region 数据分割 
                        //int strLength = data.Length;
                        //int byteLength = 10;
 
                        //if (strLength > byteLength)
                        //{
                        //    double loopNumTemp = (double)(Math.Round((decimal)(Convert.ToDecimal(strLength) / Convert.ToDecimal(byteLength)), 5));
                        //    var loopData = WebHelper.GetStr(data, byteLength);
                        //    int loopNum = 1000;
                        //    foreach (var item in loopData)
                        //    {
                        //        string loopStr = item;
                        //        if (loopNum == loopData.Count())
                        //        {
                        //            loopStr = loopStr + socketParameterModel.SpecifiedDisplay;
                        //        }
 
                        //        //string sendMessage = data + socketParameterModel.SpecifiedDisplay;
                        //        socketParameterModel.Socket.Send(Encoding.UTF8.GetBytes(loopStr));
                        //        LoggerSocketHelper.DebugLog(GetIpInfo(socketParameterModel) + "发送数据【成功】SendData:" + loopStr);
                        //        loopNum = loopNum + 1;
                        //        Thread.Sleep(2000);
                        //    }
                        //}
                        //else
                        //{
                        //    string sendMessage = data + socketParameterModel.SpecifiedDisplay;
                        //    socketParameterModel.Socket.Send(Encoding.UTF8.GetBytes(sendMessage));
                        //    LoggerSocketHelper.DebugLog(GetIpInfo(socketParameterModel) + "发送数据【成功】SendData:" + sendMessage);
                        //}
 
                        string sendMessage = data + socketParameterModel.SpecifiedDisplay;
                        //Thread.Sleep(100);
 
                        var sendNum = socketParameterModel.Socket.Send(Encoding.UTF8.GetBytes(sendMessage));
                        LoggerSocketHelper.DebugLog(GetIpInfo(socketParameterModel) + "发送数据【成功】SendData:" + sendMessage + "_sendNum:" + sendNum + "_本地端口号:" + socketParameterModel.Socket.LocalEndPoint);
                        #endregion
 
                        result = GetReceiveResult(socketParameterModel, workflow_id);
                        return result;
                    }
                    catch (Exception ex)
                    {
                        result.status = StateEnum_Equipment.Failed;
                        result.msg = GetIpInfo(socketParameterModel) + "发送数据【出错】SendData:" + ex.Message + ",StackTrace:" + ex.StackTrace;
                        LoggerSocketHelper.DebugLog(result.msg + ex);
                        return result;
                    }
                    //finally
                    //{
                    //    _socket.Blocking = blockingState;    // 恢复状态
                    //}
                }
                else
                {
                    result.status = StateEnum_Equipment.Failed;
                    result.msg = $"发送数据【出错】SendData:设备ID:{equipmentType},{ip}:{port},{equipmentId}已断开连接";
                    LoggerSocketHelper.DebugLog(result.msg);
                    return result;
                }
            }
            result.status = StateEnum_Equipment.Failed;
            result.msg = $"发送数据【出错】SendData:未获取到缓存里面的{equipmentType}数据";
            return result;
        }
        #endregion
 
        #region 获取返回数据-实际结果
        /// <summary>
        /// 获取返回数据-实际结果
        /// </summary>
        /// <param name="workflow_id">发送指令工作流ID</param>
        /// <returns></returns>
        public static Result GetReceiveResult(SocketParameterModel model, string workflow_id)
        {
            Result rModel = new Result();
            while (true)
            {
                if (model.cacheReceiveData != null && model.cacheReceiveData.Count > 0)
                {
                    CacheReceiveDataModel tempData = new CacheReceiveDataModel();
 
                    for (int i = 0; i < model.cacheReceiveData.Count; i++)
                    {
                        if (model.cacheReceiveData[i] != null && model.cacheReceiveData[i].CacheKey == workflow_id)
                        {
                            tempData = model.cacheReceiveData[i];
                            break;
                        }
                    }
 
                    if (tempData != null && !string.IsNullOrWhiteSpace(tempData.CacheKey) && tempData.CacheValue != null)
                    {
                        ResponseObject roData = tempData.CacheValue;
                        if (roData != null && roData.workflow_id == workflow_id)
                        {
                            string tempRoData = JsonConvert.SerializeObject(roData);
 
                            switch (roData.method_status)
                            {
                                case 2:
                                    rModel.status = StateEnum_Equipment.Completed;
                                    rModel.msg = "执行成功";
                                    rModel.data = new Data { json = tempRoData };
                                    break;
                                case 3:
                                    rModel.status = StateEnum_Equipment.Failed;
                                    rModel.msg = "执行失败,错误码:" + roData.error.error_code + ",错误内容:" + roData.error.error_text;
                                    rModel.data = new Data { json = tempRoData };
                                    rModel.DealWithType = EnumManagement.GetEnumValue(DealWithType_Enum.DealWithTypeBEnum).ToString();
                                    if (roData != null && roData.error != null)
                                    {
                                        rModel.ErrorMsg = new ErrorMsgModel { Error_Code = roData.error.error_code, Error_Text = roData.error.error_text, Troubleshoot = roData.error.troubleshoot };
                                        rModel.DealWithType = roData.error.dealwithtype != null ? roData.error.dealwithtype.ToString() : EnumManagement.GetEnumValue(DealWithType_Enum.DealWithTypeBEnum).ToString();
                                    }
                                    break;
                                case 4:
                                    rModel.status = StateEnum_Equipment.Canceled;
                                    rModel.msg = "任务被取消";
                                    rModel.data = new Data { json = tempRoData };
                                    break;
                                case 5:
                                    rModel.status = StateEnum_Equipment.AlarmInfo;
                                    rModel.msg = "告警信息,错误码:" + roData.error.error_code + ",错误内容:" + roData.error.error_text;
                                    rModel.data = new Data { json = tempRoData };
                                    rModel.DealWithType = EnumManagement.GetEnumValue(DealWithType_Enum.DealWithTypeBEnum).ToString();
                                    if (roData != null && roData.error != null)
                                    {
                                        rModel.ErrorMsg = new ErrorMsgModel { Error_Code = roData.error.error_code, Error_Text = roData.error.error_text, Troubleshoot = roData.error.troubleshoot };
                                        rModel.DealWithType = roData.error.dealwithtype != null ? roData.error.dealwithtype.ToString() : EnumManagement.GetEnumValue(DealWithType_Enum.DealWithTypeBEnum).ToString();
                                    }
                                    break;
                                default:
                                    rModel.status = EnumManagement.GetField<StateEnum_Equipment>(roData.method_status);
                                    rModel.msg = "返回出错";
                                    rModel.data = new Data { json = tempRoData };
                                    break;
                            }
                            LoggerSocketHelper.DebugLog(GetIpInfo(model) + $"获取返回数据【{rModel.msg},{rModel.status}】GetReceiveResult" + JsonConvert.SerializeObject(rModel));
                            return rModel;
                        }
                        //else
                        //{
                        //     LoggerSocketHelper.DebugLog(GetIpInfo() + "获取返回数据【出错】GetReceive");
                        //}
                    }
                }
 
                Thread.Sleep(100);
            }
        }
        #endregion
 
        #region 获取返回数据-sock结果
        /// <summary>
        /// 获取返回数据-sock结果
        /// </summary>
        /// <param name="_socket"></param>
        /// <param name=""></param>
        /// <returns></returns>
        public static Result GetReceive(SocketParameterModel model)
        {
            Result rModel = new Result();
            while (true)
            {
                try
                {
                    bool isCheckConnected = CheckConnected(model.Socket, model.Ip);
 
                    //if (model.Socket.Available > 0 )
                    //{
                    //    LoggerSocketHelper.DebugLog("连接状态:" + isCheckConnected + "_IP:" + model.Ip +"_端口:"+ model.Port + "_Available数据量:" + model.Socket.Available);
                    //}
 
                    if (isCheckConnected)
                    {
                        if (model.Socket.Available > 0)
                        {
                            lock (model.LockReceive)
                            {
                                int length = model.Socket.Receive(model.Buffer);
                                if (length > 0 && model.Socket.Connected)
                                {
                                    var resultMsg = Encoding.UTF8.GetString(model.Buffer, 0, length);
 
                                    if (resultMsg.Contains(model.SpecifiedDisplay) == false)   //如果结尾没有指定符号,继续获取
                                    {
                                        StringBuilder sb = new StringBuilder();
                                        sb.Append(resultMsg);
                                        while (sb.ToString().Contains(model.SpecifiedDisplay) == false)
                                        {
                                            model.Socket.Blocking = true;
 
                                            int tempLength = model.Socket.Receive(model.Buffer);
                                            if (tempLength > 0 && model.Socket.Connected)
                                            {
                                                var tempStr = Encoding.UTF8.GetString(model.Buffer, 0, tempLength);
                                                sb.Append(tempStr);
                                            }
                                        }
                                        IsLoop(model, sb.ToString());
                                    }
                                    else
                                    {
                                        IsLoop(model, resultMsg);
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    rModel.status = StateEnum_Equipment.Failed;
                    rModel.msg = GetIpInfo(model) + "获取返回数据【缓存失败】GetReceive:" + ex.Message;
                    LoggerSocketHelper.DebugLog(rModel.msg + ex);
                }
            }
            //return rModel;
        }
 
        /// <summary>
        /// 是否循环数据
        /// </summary>
        /// <param name="model"></param>
        /// <param name="resultMsg"></param>
        private static void IsLoop(SocketParameterModel model, string resultMsg)
        {
            if (!string.IsNullOrWhiteSpace(resultMsg) && resultMsg.Contains("error"))
            {
                string[] sArray = Regex.Split(resultMsg, model.SpecifiedDisplay, RegexOptions.IgnoreCase);
                if (sArray != null && sArray.Count() > 0)
                {
                    //var resultMsgBysArray = sArray.FirstOrDefault(m => m.Contains("error"));
 
                    foreach (var resultMsgBysArray in sArray)
                    {
                        var isError = resultMsgBysArray.Contains("error");
                        if (isError && !string.IsNullOrWhiteSpace(resultMsgBysArray))
                        {
                            Thread.Sleep(400);
 
                            ResponseObject roData = JsonConvert.DeserializeObject<ResponseObject>(resultMsgBysArray);
 
                            try
                            {
                                #region 插入数据到缓存中  不能插入相同值
                                if (model.cacheReceiveData != null && model.cacheReceiveData.Count > 0)
                                {
                                    object isLockAdd = new object();
                                    lock (isLockAdd)
                                    {
                                        bool isHaveValue = false;
                                        for (int i = 0; i < model.cacheReceiveData.Count; i++)
                                        {
                                            if (model.cacheReceiveData[i].CacheKey == roData.workflow_id)
                                            {
                                                isHaveValue = true;
                                                break;
                                            }
                                        }
 
                                        if (isHaveValue == false)
                                        {
                                            model.cacheReceiveData.Add(new CacheReceiveDataModel { CacheKey = roData.workflow_id, CacheValue = roData });
                                        }
                                    }
                                }
                                else
                                {
                                    model.cacheReceiveData.Add(new CacheReceiveDataModel { CacheKey = roData.workflow_id, CacheValue = roData });
                                }
                                #endregion
 
                                LoggerSocketHelper.DebugLog(GetIpInfo(model) + "获取返回数据【缓存成功】IsLoop:" + resultMsg);
                            }
                            catch (Exception ex)
                            {
                                LoggerSocketHelper.DebugLog(GetIpInfo(model) + "获取返回数据【缓存失败】IsLoop:" + resultMsg + "失败错误内容:" + ex.Message + ex);
                            }
                        }
                    }
                }
            }      //驱动返回心跳
            else if (resultMsg.Contains("equipment_status") && resultMsg.Contains("connected"))
            {
                if (resultMsg.Contains(model.SpecifiedDisplay))
                {
                    var data = JObject.Parse(resultMsg.Replace(model.SpecifiedDisplay, ""));
 
                    //获取设备ID
                    string equipmentId = model.EquipmentType + model.Ip + model.Port + model.EquipmentId;
 
                    //string equipmentId = model.EquipmentId;// data["equipment_id"].ToString();
 
                    #region 设备状态(0驱动虚拟机模式,1驱动连真机状态) 
                    bool isEquipped = data["connected"].ToString() != "0";
 
                    //设备是否存在字典中
                    if (SocketParameterModel.Dic_EquipmentConnectedStatus != null && SocketParameterModel.Dic_EquipmentConnectedStatus.Count > 0)
                    {
                        for (int i = 0; i < SocketParameterModel.Dic_EquipmentConnectedStatus.Count; i++)
                        {
                            var dicEcs = SocketParameterModel.Dic_EquipmentConnectedStatus.ElementAt(i);
 
                            if (dicEcs.Key == equipmentId)
                            {
                                //更新驱动连接设备状态
                                SocketParameterModel.Dic_EquipmentConnectedStatus[equipmentId] = isEquipped;
                            }
                        }
                    }
                    else
                    {
                        //增加驱动连接设备状态
                        SocketParameterModel.Dic_EquipmentConnectedStatus.Add(equipmentId, isEquipped);
                    }
 
                    ////设备是否存在字典中
                    //if (SocketParameterModel.Dic_EquipmentConnectedStatus.Where(m => m.Key.Equals(equipmentId)).Count() > 0)
                    //{
                    //    //更新驱动连接设备状态
                    //    SocketParameterModel.Dic_EquipmentConnectedStatus[equipmentId] = isEquipped;
                    //}
                    //else
                    //{
                    //    //增加驱动连接设备状态
                    //    SocketParameterModel.Dic_EquipmentConnectedStatus.Add(equipmentId, isEquipped);
                    //}
                    #endregion
 
                    #region 设备状态(是否忙碌  1空闲、2忙碌)
                    string equipmentStatus = data["equipment_status"].ToString() == "1" ? "空闲" : (data["equipment_status"].ToString() == "2" ? "忙碌" : "出错");
 
                    if (SocketParameterModel.Dic_EquipmentStatus != null && SocketParameterModel.Dic_EquipmentStatus.Count > 0)
                    {
                        for (int i = 0; i < SocketParameterModel.Dic_EquipmentStatus.Count; i++)
                        {
                            var dicEcs = SocketParameterModel.Dic_EquipmentStatus.ElementAt(i);
 
                            if (dicEcs.Key == equipmentId)
                            {
                                //更新驱动连接设备状态
                                SocketParameterModel.Dic_EquipmentStatus[equipmentId] = equipmentStatus;
                            }
                        }
                    }
                    else
                    {
                        //增加驱动连接设备状态
                        SocketParameterModel.Dic_EquipmentStatus.Add(equipmentId, equipmentStatus);
                    }
 
                    ////设备是否存在字典中
                    //if (SocketParameterModel.Dic_EquipmentStatus.Where(m => m.Key.Equals(equipmentId)).Count() > 0)
                    //{
                    //    SocketParameterModel.Dic_EquipmentStatus[equipmentId] = equipmentStatus;
                    //}
                    //else
                    //{
                    //    SocketParameterModel.Dic_EquipmentStatus.Add(equipmentId, equipmentStatus);
                    //}
                    #endregion
                }
            }
        }
        #endregion
        #endregion
 
        #region 业务逻辑
        #region 随机生成字符串
        /// <summary>
        /// 随机生成字符串
        /// </summary>
        /// <returns></returns>
        public static string InstrunctionId()
        {
            Random random = new Random();
            int randKey = random.Next(1000, 9999);
            string guidStr = Guid.NewGuid().ToString();
            return DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + guidStr;
        }
        #endregion
 
        #region 获取IP信息
        /// <summary>
        /// 获取IP信息
        /// </summary>
        /// <returns></returns>
        private static string GetIpInfo(SocketParameterModel model)
        {
            if (model == null)
            {
                return "获取socket参数为空【出错】GetIpInfo->";
            }
            return "IP和端口:" + model.Ip + ":" + model.Port + "->";
        }
        #endregion
        #endregion 
    }
}