Server.cs 17.7 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
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace AGVLib
{
    public class Server
    {
        internal static LogBean Log;
        //服务端
        private TcpServer server;
        //所有客户端,<ip,客户端信息>
        Dictionary<string, NodeClient> clients = new Dictionary<string, NodeClient>();
        public delegate void NodeChangedEvent(Node[] clientNodes);
        public event NodeChangedEvent NodeChanged;
        public delegate void NodeConnectedChangedEvent(string ip,bool online);
        public event NodeConnectedChangedEvent NodeConnectedChanged;
        private int serverPort;
        private List<Node> nodes = new List<Node>();
        /// <summary>
        ///  通讯服务端     
        /// </summary>
        public Server()
        {
            Log = TcpServer.Log;
        }
        public string[] LocalIp { get { return TcpServer.GetLocalAddresses(); } }
        public bool Connected { get { return server.Connected; } }
        /// <summary>
        /// 开启服务
        /// </summary>
        public void Start(int port = 12000)
        {
            try
            {
                Log.Info($"AGVServer 【{port}】服务启动");
                serverPort = port;
                server = new TcpServer(port);
                server.terminateString = "";
                server.ReviceMsgEvent += Server_ReviceMsgEvent;
                server.AcceptClientEvent += Server_AcceptClientEvent;
                server.ClientOfflineEvent += Server_ClientOfflineEvent;
                server.Start();
            }
            catch (Exception ex)
            {
                Log.Error($"AGVServer【{port}】服务启动出错", ex);
            }
        }
        /// <summary>
        /// 客户端离线事件
        /// </summary>
        /// <param name="client"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void Server_ClientOfflineEvent(TcpClientBean client)
        {
            Offline(client);
        }
        private void Offline(TcpClientBean client)
        {
            if (clients.ContainsKey(client.IP))
            {
                clients[client.IP].Client.ClientSocket = null;
                NodeConnectedChanged?.Invoke(client.IP, false);
            }
        }
        private void Online(TcpClientBean client)
        {
            if (clients.ContainsKey(client.IP))
            {
                clients[client.IP].Client = client;
                NodeConnectedChanged?.Invoke(client.IP, true);
            }
            else
            {
                clients.Add(client.IP, new NodeClient(client));
            }
        }
        /// <summary>
        /// 收到客户端连接事件
        /// </summary>
        /// <param name="client"></param>
        private void Server_AcceptClientEvent(TcpClientBean client)
        {
            Online(client);
        }

        /// <summary>
        /// 收到客户端消息事件
        /// </summary>
        /// <param name="client"></param>
        /// <param name="Msg"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void Server_ReviceMsgEvent(TcpClientBean client, string Msg, byte[] data)
        {
            Log.Debug($"收到客户端【{client.IP}:{client.Port}】的消息:【{Msg}】【{StringHelper.ToHexString(data)}】");
            if (clients.ContainsKey(client.IP))
                StickyBagHandle(clients[client.IP], data);
            else
            {
                Log.Error($"收到客户端消息,但并不存在连接信息:【{client.IP}】【{client.Port}】");
            }
        }

        /// <summary>
        /// 停止服务
        /// </summary>
        public void Stop()
        {
            try
            {
                if (server != null)
                {
                    server.Stop();
                }
                foreach (string c in clients.Keys)
                {
                    try
                    {
                        clients[c].Client.Close();
                    }
                    catch (Exception ex)
                    {
                        Log.Error(string.Format("关闭连接客户端[{0}]线程失败", c), ex);
                    }
                }
                if (clients.Count > 0) clients.Clear();

                if (nodes.Count > 0)
                    nodes.Clear();
            }
            catch (Exception ex)
            {
                Log.Error("AGVServer 服务关闭出错", ex);
            }
            Log.Error("AGVServer 服务关闭");
        }

        /// <summary>
        /// 向客户端发送命令
        /// </summary>
        /// <param name="node"></param>
        /// <returns></returns>
        public bool SendToClient(Node node)
        {
            NodeClient client = null;
            client = FindClient(node);
            if (client == null)
            {
                Log.Error("没有找到连接的节点:" + node.ToText());
                return false;
            }

            byte[] buff = Encode(node);
            bool rtn = Send(client, buff);
            Log.Info($"SendToClient【{node.ToText()}】【{rtn}】");

            return rtn;
        }
        byte[] Encode(Node node)
        {
            try
            {
                string json = JsonHelper.SerializeObject(node);
                Log.Debug(string.Format("Encode[{0}]", json));
                byte[] body = Encoding.UTF8.GetBytes(json);
                byte[] bodySize = Common.IntToByteArray(body.Length);
                byte[] buff = Common.headPack.Concat(bodySize).Concat(body).ToArray();
                return buff;
            }
            catch (Exception ex)
            {
                Log.Error("Encode Error", ex);
                return null;
            }
        }
        #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(NodeClient client, byte[] bytes)
        {
            //bytes 为系统缓冲区数据
            //bytesRead为系统缓冲区长度
            int bytesRead = bytes.Length;
            string endpoint = client.Client.IP;
            if (bytesRead > 0)
            {
                byte[] surplusBuffer = null;
                if (dic.TryGetValue(endpoint, out surplusBuffer))//已有缓存
                {
                    byte[] curBuffer = surplusBuffer.Concat(bytes).ToArray();//拼接上一次剩余的包
                    bytesRead = curBuffer.Length;
                    if (Common.CheckHeadChar(curBuffer, out int startIdx))//检查是否存在指定包头识别字符
                    {
                        byte[] tmp = new byte[bytesRead - startIdx];
                        Buffer.BlockCopy(curBuffer, startIdx, tmp, 0, bytesRead - startIdx);
                        //更新会话ID 的最新字节
                        dic.TryUpdate(endpoint, tmp, surplusBuffer);
                        surplusBuffer = curBuffer;//同步
                        Log.Debug($"拼接上一次缓存:【{StringHelper.ToHexString(surplusBuffer)}】");
                    }
                    else
                    {
                        byte[] xbtye = null;
                        dic.TryRemove(endpoint, out xbtye);
                        Log.Debug($"不拼接,因不存在头,缓存:【{StringHelper.ToHexString(surplusBuffer)}】");
                    }
                }
                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;//同步
                        Log.Debug($"第一次缓存:【{StringHelper.ToHexString(surplusBuffer)}】");
                    }
                    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];
                        if(byteSub.Length==0)//无剩下的数据包,清空缓存
                        {
                            Log.Debug($"剩余的数据包长度为0,清除缓存:【{totalLen - haveRead}】【{StringHelper.ToHexString(dic[endpoint])}】【{StringHelper.ToHexString(byteSub)}】【{StringHelper.ToHexString(surplusBuffer)}】");
                            dic.TryRemove(endpoint, out byteSub);
                            break;
                        }
                        //把剩下不够一个完整的数据包存起来
                        Buffer.BlockCopy(surplusBuffer, haveRead, byteSub, 0, totalLen - haveRead);
                        dic.TryUpdate(endpoint, byteSub, surplusBuffer);
                        surplusBuffer = byteSub;
                        Log.Debug($"剩余的数据包连一个包头的长度都不够,缓存:【{totalLen - haveRead}】【{StringHelper.ToHexString(dic[endpoint])}】【{StringHelper.ToHexString(byteSub)}】【{StringHelper.ToHexString(surplusBuffer)}】");
                        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;
                        Log.Debug($"最后一段数据不够一个完整的包,缓存:【{StringHelper.ToHexString(surplusBuffer)}】");
                        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($"粘包处理: 【{StringHelper.ToHexString(resBytes)}】");
                        if (!DecodeNode(client, resBytes))//解析失败,重新接收
                        {
                            Log.Error($"{endpoint}:解析失败");
                            return;
                        }
                        //依次累加当前的数据包的长度
                        haveRead = haveRead + Common.headSize + bodySize;
                        if (Common.headSize + bodySize == bytesRead)//如果当前接收的数据包长度正好等于缓冲区长度,则待拼接的不规则数据长度归0
                        {
                            byte[] xbtye = null;
                            dic.TryRemove(endpoint, out xbtye);
                            surplusBuffer = null;//设置空 回到原始状态
                            totalLen = 0;//清0
                            Log.Debug($"清空缓存");
                        }

                    }

                }

            }

        }
        #endregion
        Node Decode(byte[] buff)
        {
            try
            {
                string json = System.Text.Encoding.UTF8.GetString(buff);
                Log.Debug(string.Format("Decode【{0}】", json));
                Node node = JsonHelper.DeserializeJsonToObject<Node>(json);

                return node;
            }
            catch (Exception ex)
            {
                Log.Error("Decode Error", ex);
                return null;
            }
        }
        /// <summary>
        /// 解析收到的字节码
        /// </summary>
        /// <param name="client"></param>
        /// <param name="resultBytes"></param>
        /// <returns></returns>
        private bool DecodeNode(NodeClient client, byte[] resultBytes)
        {
            Node node = Decode(resultBytes);
            if (node == null)
            {
                Log.Error("命令解析失败: " + StringHelper.ToHexString(resultBytes));
                return false;
            }
            else
            {
                if (node.id == 0) node.remark = client.Client.IP;
                int idx = client.Nodes.FindIndex(s => s.id.Equals(node.id));
                if (idx == -1) client.Nodes.Add(node);
                UpdateNode(node);
                return true;
            }

        }
        /// <summary>
        /// 查找客户端
        /// 客户端是一个IP对应一个节点
        /// 客户端是一个IP上有多个节点,使用节点Id
        /// </summary>
        /// <param name="nodeIp">节点</param>
        /// <returns></returns>
        private NodeClient FindClient(Node node)
        {
            if (node.id.Equals(0))//客户端是一个IP对应一个节点
            {
                if (clients.ContainsKey(node.remark))
                {
                    return clients[node.remark];
                }
            }
            else//客户端是一个IP上有多个节点,使用节点Id
            {
                foreach (NodeClient item in clients.Values)
                {
                    int idx = item.Nodes.FindIndex(s => s.id.Equals(node.id));
                    if (idx >= 0)
                        return item;
                }
            }
            return null;
        }
        /// <summary>
        /// 是否已存在节点
        /// </summary>
        /// <param name="node"></param>
        /// <returns></returns>
        private bool FindNode(Node node, out Node existNode)
        {
            int idx = -1;
            if(node.id.Equals(0))
            {
                idx= nodes.FindIndex(s => s.id.Equals(node.id) && s.remark.Equals(node.remark));
            }
            else
            {
                idx = nodes.FindIndex(s => s.id.Equals(node.id) && s.name.Equals(node.name));
            }
            existNode = idx == -1 ? null : nodes[idx];
            return existNode!=null ? true : false;
        }
        /// <summary>
        /// 更新节点状态
        /// </summary>
        /// <param name="node"></param>
        private void UpdateNode(Node node)
        {
            if (!FindNode(node, out Node findnode))
            {
                nodes.Add(node);
                NodeChanged?.Invoke(nodes.ToArray());
                Log.Info(string.Format("节点添加并状态更新[{0}]", node.ToText()));
            }
            else if (!findnode.Equals(node))
            {
                findnode.SetState(node.status, node.level, node.shelf_id, node.remark);
                NodeChanged?.Invoke(nodes.ToArray());
                Log.Info(string.Format("节点状态更新[{0}]", node.ToText()));
            }

        }

        /// <summary>
        /// 发送命令
        /// </summary>
        /// <param name="client"></param>
        /// <param name="buff"></param>
        /// <returns></returns>
        private bool Send(NodeClient client, byte[] buff)
        {
            for (int i = 1; i <= 3; i++)
            {
                try
                {
                    client.Send(buff);
                    return true;
                }
                catch (Exception ex)
                {
                    Log.Error("发送失败" + i + "次:" + ex.Message);
                }
                Thread.Sleep(100);
            }
            return false;
        }



        private class NodeClient
        {
            public List<Node> Nodes;
            public TcpClientBean Client;
            public bool Send(byte[] data)
            {
                if (Client.ClientSocket != null && Client.ClientSocket.Connected)
                {
                    Client.ClientSocket.Send(data);
                    return true;
                }
                return false;
            }
            public NodeClient(TcpClientBean client)
            {
                Client = client;
                Nodes = new List<Node>();
            }
        }
    }
}