Server.cs 23.5 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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Dolen;
namespace Dolen.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>();

        private static Log log = new Log();
        /// <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($"AGV 服务端开启:{ip}:{port}");
                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;
                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($"AGV 服务端开启:{ip}:{port}", 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 (nodeMap.Count > 0)
                    nodeMap.Clear();

                if (_server != null)
                {
                    _server.Close();
                    _server.Dispose();
                }
            }
            catch (Exception ex)
            {
                log.Error("AGV 服务端关闭", ex);
            }

        }

        /// <summary>
        /// 向客户端发送命令
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public bool SendToClient(int id, 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;
                    if (dictClient.TryGetValue(ip, out Client client1))
                    {
                        Offline(client1);
                        Thread.Sleep(2000);
                        log.debug(string.Format("断开"));
                    }
                    Thread thr = new Thread(ListenNet);
                    Client client = new Client(sokConnection, thr, ip, endPoint.ToString());
                    thr.IsBackground = true;
                    dictClient.Add(ip, client);
                    thr.Start(client);
                    log.info(string.Format("客户端[{0}]连接服务端[{1}]成功", endPoint.ToString(), ServerInfo));
                }
                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))
                {
                    byte[] curBuffer = surplusBuffer.Concat(bytes).ToArray();//拼接上一次剩余的包
                    if (Common.CheckHeadChar(bytes, out int startIdx))//检查是否存在指定包头识别字符
                    {
                        byte[] tmp = new byte[bytesRead - startIdx];
                        Buffer.BlockCopy(bytes, startIdx, tmp, 0, bytesRead - startIdx);
                        //更新会话ID 的最新字节
                        dic.TryUpdate(endpoint, tmp, surplusBuffer);
                        surplusBuffer = curBuffer;//同步
                    }
                    else
                    {
                        byte[] xbtye = null;
                        dic.TryRemove(endpoint, out xbtye);
                    }
                }
                else
                {
                    if (Common.CheckHeadChar(bytes, out int startIdx))//检查是否存在指定包头识别字符
                    {
                        //添加会话ID的bytes
                        byte[] tmp = new byte[bytesRead - startIdx];
                        Buffer.BlockCopy(bytes, startIdx, tmp, 0, bytesRead - startIdx);
                        dic.TryAdd(endpoint, tmp);
                        surplusBuffer = tmp;//同步
                    }
                    else
                        return;
                }

                //已经完成读取每个数据包长度
                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;

                        break;

                    }

                    //如果够了一个完整包,则读取包头的数据
                    byte[] headByte = new byte[Common.headSize];
                    Buffer.BlockCopy(surplusBuffer, haveRead, headByte, 0, Common.headSize);//从缓冲区里读取包头的字节
                                                                                            //判断包头起始符
                    int bodySize = BitConverter.ToUInt16(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;
                        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("[Receive data from:{0}] -> {1}", endpoint, Common.HexBuff(resBytes)));
                        DecodeNode(client, resBytes);
                        //依次累加当前的数据包的长度
                        haveRead = haveRead + Common.headSize + bodySize;
                        if (Common.headSize + bodySize == bytesRead)//如果当前接收的数据包长度正好等于缓冲区长度,则待拼接的不规则数据长度归0
                        {
                            byte[] xbtye = null;
                            dic.TryRemove(endpoint, out xbtye);
                            surplusBuffer = null;//设置空 回到原始状态
                            totalLen = 0;//清0
                        }

                    }

                }

            }

        }
        #endregion
        private void DecodeNode(Client client, byte[] resultBytes)
        {
            //解码单个节点
            if (Common.EnDecodeSingleNode)
            {
                Node node = Common.Decode(resultBytes);
                if (node == null)
                {
                    log.error("命令解析失败: " + Common.HexBuff(resultBytes));
                }
                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);

                }
            }
            else
            {
                //解码多个节点
                List<Node> nodes = Common.DecodeNodes(resultBytes);
                if (nodes == null)
                {
                    log.error("命令解析失败: " + Common.HexBuff(resultBytes));
                }
                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);
                }
            }
        }
        /// <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);
                        StickyBagHandle(client, buff);
                    }
                }
                catch (Exception e)
                {

                }
            }
        }
        /// <summary>
        /// 查找客户端
        /// </summary>
        /// <param name="nodeName"></param>
        /// <returns></returns>
        private string FindClient(int id)
        {
            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.debug(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;
                dictClient.Remove(client.IP);
                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);
                    }

                    if (nodeMap.ContainsKey(client.nodeName[i]))
                        nodeMap.Remove(client.nodeName[i]);
                }
                client.nodeName.Clear();
                client.ListenNet.Abort();
                log.info(string.Format("关闭对客户端[{0}]的监听线程", client.Endpoint));
            }
            catch (ThreadAbortException)
            {
                log.error(string.Format("关闭对客户端[{0}]的监听线程", 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;
            dictClient.Remove(client.IP);
        }

        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)
                    {
                        Send(client, buff);
                    }
                }
                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);
                    log.debug(string.Format("服务端[{0}]向客户端[{1}]发送消息:[{2}]", ServerInfo, clientKey, Common.HexBuff(buff)));
                    return true;
                }
                catch (Exception ex)
                {
                    log.error("发送失败" + i + "次:" + ex.Message);
                }
                Thread.Sleep(100);
            }
            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>();
            }
        }
    }
}