AgvServer.cs
28.0 KB
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
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.Eventing.Reader;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Agv
{
public class Server
{
private bool loop;
private Socket _server; //服务端
Dictionary<string, Client> dictClient = new Dictionary<string, Client>(); //所有客户端
private Thread tListenClient; //监听客户端连接
private Thread tKeepLive;//心跳线程
private Dictionary<string, bool> nodeOnline = new Dictionary<string, bool>();
public delegate void NodeChangedEvent(Node clientNode);
public delegate void NodeOnlineEvent(string nodeName, bool online);
public event NodeChangedEvent NodeChanged;
public event NodeOnlineEvent NodeOnline;
private string serverIp;
private int serverPort;
private Dictionary<string, Node> nodeMap = new Dictionary<string, Node>();
/// <summary>
///
/// </summary>
/// <param name="_IsdecodeSingleNode">解码方式,默认解码多个节点</param>
public Server()
{
}
/// <summary>
/// 服务端信息
/// </summary>
public string ServerInfo
{
get
{
return string.Format("{0}:{1}", serverIp, serverPort.ToString());
}
}
/// <summary>
/// 开启服务
/// </summary>
public void Start(string ip = "0.0.0.0", int port = 12000)
{
try
{
log.info("AGVServer服务启动");
serverIp = ip;
serverPort = port;
IPEndPoint localEP;
if (ip.Equals("0.0.0.0"))
localEP = new IPEndPoint(IPAddress.Any, serverPort);
else
localEP = new IPEndPoint(IPAddress.Parse(ip), serverPort);
_server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_server.Bind(localEP);
_server.Listen(100);
loop = true;
//_client = new List<Client>();
tListenClient = new Thread(new ThreadStart(ListenClient));
tListenClient.IsBackground = true;
tListenClient.Start();
tKeepLive = new Thread(new ThreadStart(KeepClientLive));
tKeepLive.IsBackground = true;
tKeepLive.Start();
}
catch (Exception ex)
{
log.error("AGVServer服务启动", ex);
}
}
/// <summary>
/// 停止服务
/// </summary>
public void Stop()
{
try
{
loop = false;
foreach (string c in dictClient.Keys)
{
try
{
dictClient[c].ListenNet.Abort();
}
catch (Exception ex)
{
log.error(string.Format("关闭连接客户端[{0}]线程失败", c), ex);
}
try
{
dictClient[c].Socket.Close();
}
catch (Exception ex)
{
log.error(string.Format("关闭连接客户端[{0}]Socket失败", c), ex);
}
}
if (dictClient.Count > 0) dictClient.Clear();
if (_server != null)
{
_server.Close();
_server.Dispose();
}
}
catch (Exception ex)
{
log.error("AGVServer服务关闭", ex);
}
}
/// <summary>
/// 向服务端发送命令
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
public bool SendToClient(string nodeName, string RFID, ClientAction action)
{
string tar = "";
int n = 0;
do
{
tar = FindClient(nodeName);
if (tar.Equals(""))
{
log.error("没有找到" + nodeName);
Thread.Sleep(500);
n++;
}
else
{
n = 10;
}
} while (n < 4);
if (tar.Equals("")) return false;
Node node = new Node(nodeName, RFID, action);
log.info("SendTo " + nodeName + " RFID=" + RFID + " " + action);
byte[] buff = Common.Encode(node);
return Send(tar, buff);
}
/// <summary>
/// 小车到达
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
public bool Arrive(string nodeName, string RFID = "")
{
string tar = "";
int n = 0;
do
{
tar = FindClient(nodeName);
if (tar.Equals(""))
{
log.error("Arrive: 没有找到" + nodeName);
Thread.Sleep(500);
n++;
}
else
{
n = 10;
}
} while (n < 4);
if (tar.Equals("")) return false;
Node node = new Node(nodeName, RFID, ClientAction.Arrive);
log.info("SendTo " + nodeName + " RFID=" + RFID + " " + ClientAction.Arrive);
byte[] buff = Common.Encode(node);
return Send(tar, buff);
}
/// <summary>
/// 小车已准备好
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
public bool Ready(string nodeName, string RFID = "")
{
string tar = "";
int n = 0;
do
{
tar = FindClient(nodeName);
if (tar.Equals(""))
{
log.error("Ready: 没有找到" + nodeName);
Thread.Sleep(500);
n++;
}
else
{
n = 10;
}
} while (n < 4);
if (tar.Equals("")) return false;
Node node = new Node(nodeName, RFID, ClientAction.Ready);
log.info("SendTo " + nodeName + " RFID=" + RFID + " " + ClientAction.Ready);
byte[] buff = Common.Encode(node);
return Send(tar, buff);
}
/// <summary>
/// 关门
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
public bool CloseDoor(string nodeName, string RFID = "")
{
string tar = "";
int n = 0;
do
{
tar = FindClient(nodeName);
if (tar.Equals(""))
{
log.debug("CloseDoor: 没有找到" + nodeName);
Thread.Sleep(500);
n++;
}
else
{
n = 10;
}
} while (n < 4);
if (tar.Equals("")) return false;
Node node = new Node(nodeName, RFID, ClientAction.CloseDoor);
log.info("SendTo " + nodeName + " RFID=" + RFID + " " + ClientAction.CloseDoor);
byte[] buff = Common.Encode(node);
return Send(tar, buff);
}
/// <summary>
/// 监听客户端连接
/// </summary>
private void ListenClient()
{
while (loop)
{
try
{
// 开始监听客户端连接请求,Accept方法会阻断当前的线程;
Socket sokConnection = _server.Accept(); // 一旦监听到一个客户端的请求,就返回一个与该客户端通信的 套接字;
IPEndPoint endPoint = (IPEndPoint)sokConnection.RemoteEndPoint;
string ip = endPoint.Address.ToString();
int port = endPoint.Port;
Thread thr = new Thread(ListenNet);
Client client = new Client(sokConnection, thr, ip, endPoint.ToString());
thr.IsBackground = true;
if (dictClient.TryGetValue(ip, out Client client1))
{
log.info(string.Format($"{ip}重连 断开上一次连接:{client1.Endpoint}"));
Offline(client1);
dictClient[ip] = client;
}
else
dictClient.Add(ip, client);
thr.Start(client);
log.info(string.Format("客户端[{0}]连接服务端[{1}]成功", endPoint.ToString(), ServerInfo));
Thread.Sleep(300);
}
catch (SocketException)
{
//关闭连接,退出阻塞Accept
}
catch (Exception ex)
{
log.error("ListenClient", ex);
}
}
}
#region 粘包处理
//线程安全的字典
ConcurrentDictionary<string, byte[]> dic = new ConcurrentDictionary<string, byte[]>();
/// <summary>
/// 处理客户端发来的数据
/// </summary>
/// <param name="obj">每个客户的会话ID</param>
/// <param name="bytes">缓冲区数据</param>
/// <returns></returns>
private void StickyBagHandle(Client client, byte[] bytes)
{
//bytes 为系统缓冲区数据
//bytesRead为系统缓冲区长度
int bytesRead = bytes.Length;
string endpoint = client.IP;
if (bytesRead > 0)
{
byte[] surplusBuffer = null;
if (dic.TryGetValue(endpoint, out surplusBuffer))
{
log.debug($"拼接上次剩余包【{endpoint}】:【{Common.HexBuff(surplusBuffer)}】+【{Common.HexBuff(bytes)}】");
byte[] curBuffer = surplusBuffer.Concat(bytes).ToArray();//拼接上一次剩余的包
//更新会话ID 的最新字节
dic.TryUpdate(endpoint, curBuffer, surplusBuffer);
surplusBuffer = curBuffer;//同步
}
else
{
//添加会话ID的bytes
dic.TryAdd(endpoint, bytes);
log.debug($"新数据【{endpoint}】:【{Common.HexBuff(bytes)}】");
surplusBuffer = bytes;//同步
}
//判断包头起始符
if (!Common.CheckHeadChar(surplusBuffer, out int startIdx))
{
dic.TryRemove(endpoint, out _);
log.debug($"未找到包头,删除缓存【{endpoint}】:【{Common.HexBuff(surplusBuffer)}】");
surplusBuffer = null;//设置空 回到原始状态
return;
}
else
{
if(startIdx>0)
{
log.debug($"找到包头,但不在起始位置【{startIdx}】【{endpoint}】:【{Common.HexBuff(surplusBuffer)}】");
byte[] subByte= new byte[surplusBuffer.Length-startIdx+1];
Buffer.BlockCopy(surplusBuffer, startIdx, subByte, 0, subByte.Length);//从缓冲区里读取包头的字节
dic.TryUpdate(endpoint, subByte, surplusBuffer);
surplusBuffer = subByte;//同步
log.debug($"找到包头,不在起始位置处理完成【{endpoint}】:【{Common.HexBuff(surplusBuffer)}】");
}
}
//已经完成读取每个数据包长度
int haveRead = 0;
//这里totalLen的长度有可能大于缓冲区大小的(因为 这里的surplusBuffer 是系统缓冲区+不完整的数据包)
int totalLen = surplusBuffer.Length;
while (haveRead <= totalLen)
{
//如果在N次拆解后剩余的数据包连一个包头的长度都不够
//说明是上次读取N个完整数据包后,剩下的最后一个非完整的数据包
if (totalLen - haveRead < Common.headSize)
{
byte[] byteSub = new byte[totalLen - haveRead];
//把剩下不够一个完整的数据包存起来
Buffer.BlockCopy(surplusBuffer, haveRead, byteSub, 0, totalLen - haveRead);
dic.TryUpdate(endpoint, byteSub, surplusBuffer);
surplusBuffer = byteSub;
totalLen = 0;
log.debug($"剩余包长度不够包头,保存【{endpoint}】:【{Common.HexBuff(byteSub)}】");
break;
}
//如果够了一个完整包,则读取包头的数据
byte[] headByte = new byte[Common.headSize];
Buffer.BlockCopy(surplusBuffer, haveRead, headByte, 0, Common.headSize);//从缓冲区里读取包头的字节
int bodySize = BitConverter.ToInt32(headByte, 2);//从包头里面分析出包体的长度
//这里的 haveRead=等于N个数据包的长度 从0开始;0,1,2,3....N
//如果自定义缓冲区拆解N个包后的长度 大于 总长度,说最后一段数据不够一个完整的包了,拆出来保存
if (haveRead + Common.headSize + bodySize > totalLen)
{
byte[] byteSub = new byte[totalLen - haveRead];
Buffer.BlockCopy(surplusBuffer, haveRead, byteSub, 0, totalLen - haveRead);
dic.TryUpdate(endpoint, byteSub, surplusBuffer);
surplusBuffer = byteSub;
log.debug($"解析剩余数据不足一个完整包,保存剩余【{endpoint}】:【{Common.HexBuff(byteSub)}】");
break;
}
else
{
//挨个分解每个包,解析成实际文字
//String strc = Encoding.UTF8.GetString(surplusBuffer, haveRead + headSize, bodySize);
byte[] resBytes = new byte[bodySize];
Buffer.BlockCopy(surplusBuffer, haveRead + Common.headSize, resBytes, 0, bodySize);
log.debug(string.Format("[解析数据:{0}]:{1}", endpoint, Common.HexBuff(resBytes)));
if (!DecodeNode(client, resBytes))//解析失败,清空缓存
{
log.error($"解析失败【{endpoint}】:【{Common.HexBuff(resBytes)}】");
dic.TryRemove(endpoint, out byte[] xbtye);
log.debug($"删除剩余缓存【{endpoint}】:【{Common.HexBuff(xbtye)}】");
surplusBuffer = null;//设置空 回到原始状态
totalLen = 0;//清0
return;
}
//依次累加当前的数据包的长度
haveRead = haveRead + Common.headSize + bodySize;
if (Common.headSize + bodySize == bytesRead)//如果当前接收的数据包长度正好等于缓冲区长度,则待拼接的不规则数据长度归0
{
dic.TryRemove(endpoint, out byte[] xbtye);
log.debug($"接收的数据长度{bytesRead}一次解析完成,删除缓存【{endpoint}】:【{Common.HexBuff(bytes)}】【{Common.HexBuff(xbtye)}】");
surplusBuffer = null;//设置空 回到原始状态
totalLen = 0;//清0
return;
}
}
}
}
}
#endregion
private bool DecodeNode(Client client, byte[] resultBytes)
{
//解码单个节点
if (Common.EnDecodeSingleNode)
{
Node node = Common.Decode(resultBytes);
if (node == null)
{
//log.error("命令解析失败: " + Common.HexBuff(resultBytes));
return false;
}
else
{
//CommonVar.LogUtil.info("Receive[" + client.IP + "] " + node.ToText());
int idx = client.nodeName.FindIndex(s => s == node.Name);
if (idx == -1) client.nodeName.Add(node.Name);
UpdateNode(node);
return true;
}
}
else
{
//解码多个节点
List<Node> nodes = Common.DecodeNodes(resultBytes);
if (nodes == null)
{
//log.error("命令解析失败: " + Common.HexBuff(resultBytes));
return false;
}
else
{
int idx = -1;
foreach (var node in nodes)
{
idx = client.nodeName.FindIndex(s => s == node.Name);
if (idx == -1) client.nodeName.Add(node.Name);
}
UpdateNodes(nodes);
return true;
}
}
}
/// <summary>
/// 客户端数据接收
/// </summary>
/// <param name="obj">索引</param>
private void ListenNet(object obj)
{
Client client = obj as Client;
Socket sokClient = client.Socket;
while (client.Loop)
{
Thread.Sleep(100);
try
{
// 定义一个缓存区;
byte[] arrMsgRec = new byte[1024];
// 将接收到的数据存入到输入 arrMsgRec中;
int length = -1;
if (!client.Loop) return;
if (sokClient != null && sokClient.Poll(-1, SelectMode.SelectRead))
{
length = sokClient.Receive(arrMsgRec); // 接收数据,并返回数据的长度;
if (length == 0)//连接正常断开
{
Offline(client);
log.info(string.Format("客户端[{0}]断开与服务端[{1}]的连接", sokClient.RemoteEndPoint.ToString(), ServerInfo));
return;
}
}
if (length > 0)
{
byte[] buff = new byte[length];
Array.Copy(arrMsgRec, 0, buff, 0, length);
log.debug(string.Format("[Receive data from:{0}] -> {1}", client.Endpoint, Common.HexBuff(buff)));
StickyBagHandle(client, buff);
}
}
catch (Exception e)
{
log.error($"ListenNet error,{client.IP}", e);
}
}
}
private string FindClient(string nodeName)
{
foreach (string item in dictClient.Keys)
{
if (dictClient[item].nodeName.Contains(nodeName))
return item;
}
return "";
}
private void UpdateNode(Node node)
{
if (!nodeOnline.Keys.Contains(node.Name))
{
nodeOnline.Add(node.Name, true);
NodeOnline?.Invoke(node.Name, true);
}
else if (nodeOnline[node.Name].Equals(false))
{
nodeOnline[node.Name] = true;
NodeOnline?.Invoke(node.Name, true);
}
if (!nodeMap.Keys.Contains(node.Name))
{
nodeMap.Add(node.Name, node);
NodeChanged?.Invoke(node);
log.info(string.Format("节点添加并状态更新[{0}]", node.ToText()));
}
else if (!nodeMap[node.Name].Equals(node))
{
nodeMap[node.Name] = node;
NodeChanged?.Invoke(node);
log.info(string.Format("节点状态更新[{0}]", node.ToText()));
}
}
private void UpdateNodes(List<Node> nodes)
{
foreach (var node in nodes)
{
UpdateNode(node);
Thread.Sleep(200);
}
}
private void Offline(Client client)
{
try
{
client.Loop = false;
if (client.Socket != null)
{
client.Socket.Close();
client.Socket = null;
}
for (int i = 0; i < client.nodeName.Count; i++)
{
if (!nodeOnline.Keys.Contains(client.nodeName[i]))
{
nodeOnline.Add(client.nodeName[i], false);
NodeOnline?.Invoke(client.nodeName[i], false);
}
else if (nodeOnline[client.nodeName[i]].Equals(true))
{
nodeOnline[client.nodeName[i]] = false;
NodeOnline?.Invoke(client.nodeName[i], false);
}
}
client.nodeName.Clear();
client.ListenNet.Abort();
log.info(string.Format("关闭对客户端[{0}]的监听线程1", client.Endpoint));
}
catch (ThreadAbortException)
{
log.error(string.Format("关闭对客户端[{0}]的监听线程1", client.Endpoint));
}
}
private void Offline(string clientKey)
{
if (!dictClient.Keys.Contains(clientKey))
return;
Client client = dictClient[clientKey];
client.Loop = false;
client.Socket.Close();
for (int i = 0; i < client.nodeName.Count; i++)
{
if (!nodeOnline.Keys.Contains(client.nodeName[i]))
{
nodeOnline.Add(client.nodeName[i], false);
NodeOnline?.Invoke(client.nodeName[i], false);
}
else if (nodeOnline[client.nodeName[i]].Equals(true))
{
nodeOnline[client.nodeName[i]] = false;
NodeOnline?.Invoke(client.nodeName[i], false);
}
}
client.nodeName.Clear();
client.ListenNet.Abort();
client.Socket = null;
log.info(string.Format("关闭对客户端[{0}]的监听线程2", client.Endpoint));
}
private void KeepClientLive()
{
Node node = new Node("", "Heartbeat package", ClientAction.None);
byte[] buff = Common.Encode(node);
while (loop)
{
try
{
Thread.Sleep(2000);
foreach (string client in dictClient.Keys)
{
SendLive(client, buff);
Thread.Sleep(1000);
}
}
catch (Exception ex)
{
}
}
}
/// <summary>
/// 发送命令
/// </summary>
/// <param name="idx"></param>
/// <param name="buff"></param>
/// <returns></returns>
private bool Send(string clientKey, byte[] buff)
{
for (int i = 1; i <= 3; i++)
{
try
{
dictClient[clientKey].Socket.Send(buff);
return true;
}
catch (Exception ex)
{
log.error($"给{clientKey}发送失败" + i + "次:" + ex.Message);
}
Thread.Sleep(100);
}
Offline(clientKey);
return false;
}
private bool SendLive(string clientKey, byte[] buff)
{
try
{
if (dictClient[clientKey].Loop)
dictClient[clientKey].Socket.Send(buff);
return true;
}
catch (Exception ex)
{
log.error($"给{clientKey}发送心跳包失败" + ex.Message);
}
Offline(clientKey);
return false;
}
private class Client
{
public bool Loop;
public string Endpoint;
public string IP;
public List<string> nodeName;
public Socket Socket;
public Thread ListenNet;
public Client(Socket socket, Thread thread, string ip, string Endpoint)
{
Socket = socket;
ListenNet = thread;
Loop = true;
IP = ip;
this.Endpoint = Endpoint;
nodeName = new List<string>();
}
}
}
/// <summary>
/// 客户端的节点
/// </summary>
public class ClientNode : Node
{
/// <summary>
/// 在线状态
/// </summary>
public bool Online { get; set; }
/// <summary>
/// 是否可调用
/// </summary>
public bool IsUse { set; get; }
public string AliceName { get; set; }
/// <summary>
/// 线体名
/// </summary>
public string LineName { set; get; }
/// <summary>
/// 客户端的节点
/// </summary>
public ClientNode() : base()
{
}
public ClientNode(string nodeName, string rfid, ClientAction clientAction) : base(nodeName)
{
RFID = rfid;
Action = clientAction;
}
/// <summary>
/// 客户端节点
/// </summary>
/// <param name="name"></param>
/// <param name="ip"></param>
/// <param name="isUse"></param>
//public ClientNode(string name, string aliceName, bool isUse, int priority = 0) : base(name)
//{
// AliceName = aliceName;
// Online = false;
// IsUse = isUse;
// Priority = priority;
//}
/// <summary>
/// 客户端节点
/// </summary>
/// <param name="name"></param>
/// <param name="ip"></param>
/// <param name="isUse"></param>
public ClientNode(string name, string aliceName, string lineName, bool isUse) : base(name)
{
LineName = lineName;
AliceName = aliceName;
Online = false;
IsUse = isUse;
}
/// <summary>
/// 客户端节点
/// </summary>
/// <param name="name"></param>
/// <param name="rfid"></param>
/// <param name="action"></param>
/// <param name="level"></param>
public ClientNode(string name, string rfid = "", string mark = "", ClientAction action = ClientAction.None, Agv.ClientLevel level = Agv.ClientLevel.Low) : base(name)
{
RFID = rfid;
Mark = mark;
Level = level;
Action = action;
}
/// <summary>
/// 脱机
/// </summary>
public void Offline()
{
RFID = "";
Action = ClientAction.None;
Online = false;
}
}
}