Server.cs 13.1 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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using Model;

namespace BLL
{
    public class Server
    {
        private string _ip;             //本地IP地址
        private Socket _server;         //服务端
        private List<Client> _client;   //所有客户端
        private Timer timerListenClient;
        private const int PORT = 12000;    //端口

        public Server(string localIP)
        {
            _ip = localIP;
            _client = new List<Client>();
            Common.nodeInfos = new List<ClientNode>();
            ThreadPool.SetMaxThreads(20, 20);  //线程池最大数量
        }

        /// <summary>
        /// 开启服务
        /// </summary>
        public void Start()
        {
            try
            {
                IPEndPoint localEP = new IPEndPoint(IPAddress.Any, PORT);
                _server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                _server.Bind(localEP);
                _server.Listen(100);

                _client = new List<Client>();
                timerListenClient = new Timer(ListenClient, null, 50, Timeout.Infinite);
                Common.log.Info("AGV服务启动");
            }
            catch (Exception ex)
            {
                Common.log.Error("Start", ex);
            }
        }

        /// <summary>
        /// 停止服务
        /// </summary>
        public void Stop()
        {
            for (int i = 0; i < _client.Count; i++)
                _client[i].Clear();
            if (timerListenClient != null)
                timerListenClient.Dispose();
            Common.log.Info("AGV服务关闭");
        }

        /// <summary>
        /// 更新节点界面
        /// </summary>
        /// <param name="nodeIndex"></param>
        public void NodeRefresh(int nodeIndex)
        {
            //NodeChanged?.Invoke(nodeIndex);
        }

        ///// <summary>
        ///// 小车到达
        ///// </summary>
        ///// <param name="info"></param>
        ///// <returns></returns>
        //public bool Arrive(Agv_Info info)
        //{
        //    //int idx;
        //    //int n = 0;
        //    //do
        //    //{
        //    //    idx = FindClient(info.Place);
        //    //    if (idx == -1)
        //    //    {
        //    //        Common.log.Info("没有找到" + info.Place);
        //    //        Thread.Sleep(500);
        //    //        n++;
        //    //    }
        //    //    else
        //    //    {
        //    //        n = 10;
        //    //    }
        //    //} while (n < 4);
        //    //if (idx == -1) return false;

        //    //ClientNode node = new ClientNode(info.Place, info.RFID, ClientAction.Arrive);
        //    //Common.log.Info("SendTo " + info.Place + " " + ClientAction.Arrive);
        //    //byte[] buff = Encode(node);
        //    //return Send(idx, buff);
        //}

        ///// <summary>
        ///// 小车已准备好
        ///// </summary>
        ///// <param name="info"></param>
        ///// <returns></returns>
        //public bool Ready(Agv_Info info)
        //{
        //    //int idx;
        //    //int n = 0;
        //    //do
        //    //{
        //    //    idx = FindClient(info.Place);
        //    //    if (idx == -1)
        //    //    {
        //    //        Common.log.Info("没有找到" + info.Place);
        //    //        Thread.Sleep(500);
        //    //        n++;
        //    //    }
        //    //    else
        //    //    {
        //    //        n = 10;
        //    //    }
        //    //} while (n < 4);
        //    //if (idx == -1) return false;

        //    //ClientNode node = new ClientNode(info.Place, info.RFID, ClientAction.Ready);
        //    //Common.log.Info("SendTo " + info.Place + " " + ClientAction.Ready);
        //    //byte[] buff = Encode(node);
        //    //return Send(idx, buff);
        //}

        ///// <summary>
        ///// 关门
        ///// </summary>
        ///// <param name="info"></param>
        ///// <returns></returns>
        //public bool CloseDoor(Agv_Info info)
        //{
        //    //int idx;
        //    //int n = 0;
        //    //do
        //    //{
        //    //    idx = FindClient(info.Place);
        //    //    if (idx == -1)
        //    //    {
        //    //        Common.log.Info("没有找到" + info.Place);
        //    //        Thread.Sleep(500);
        //    //        n++;
        //    //    }
        //    //    else
        //    //    {
        //    //        n = 10;
        //    //    }
        //    //} while (n < 4);
        //    //if (idx == -1) return false;

        //    //ClientNode node = new ClientNode(info.Place, info.RFID, ClientAction.CloseDoor);
        //    //Common.log.Info("SendTo " + info.Place + " " + ClientAction.CloseDoor);
        //    //byte[] buff = Encode(node);
        //    //return Send(idx, buff);
        //}

        ///// <summary>
        ///// 需要进入料架
        ///// </summary>
        ///// <param name="info"></param>
        ///// <returns></returns>
        //public bool EnterShelf(Agv_Info info)
        //{
        //    //int idx;
        //    //int n = 0;
        //    //do
        //    //{
        //    //    idx = FindClient(info.Place);
        //    //    if (idx == -1)
        //    //    {
        //    //        Common.log.Info("没有找到" + info.Place);
        //    //        Thread.Sleep(500);
        //    //        n++;
        //    //    }
        //    //    else
        //    //    {
        //    //        n = 10;
        //    //    }
        //    //} while (n < 4);
        //    //if (idx == -1) return false;

        //    //ClientNode node = new ClientNode(info.Place, info.RFID, ClientAction.EnterShelf);
        //    //Common.log.Info("SendTo " + info.Place + " " + ClientAction.EnterShelf);
        //    //byte[] buff = Encode(node);
        //    //return Send(idx, buff);
        //}






        /// <summary>
        /// 监听客户端
        /// </summary>
        private void ListenClient(object obj)
        {
            try
            {
                Socket socket = _server.Accept();
                IPEndPoint ep = (IPEndPoint)socket.RemoteEndPoint;
                string ip = ep.Address.ToString();
                if (ip == _ip) ip += ":" + ep.Port;

                //重连后关闭旧连接
                int idx = _client.FindIndex(s => s.IP == ip);
                if (idx > -1)
                {
                    _client[idx].Clear();
                    _client.RemoveAt(idx);
                }

                //新的客户端
                Client client = new Client { IP = ip, IsConn = true, Socket = socket };
                _client.Add(client);
                client.ListenNet = new Timer(ListenNet, _client.Count - 1, 100, 100);
                Common.log.Info(string.Format("[{0}] 已连接", client.IP));
            }
            catch (SocketException)
            {
                //关闭连接,退出阻塞Accept
            }
            catch (Exception ex)
            {
                Common.log.Error("ListenClient", ex);
            }
        }

        /// <summary>
        /// 客户端数据接收
        /// </summary>
        /// <param name="obj">索引</param>
        private void ListenNet(object obj)
        {
            Client client = _client[(int)obj];
            byte[] temp = new byte[200];
            int time = 0;

            try
            {
                if (client.Socket.Available > 0)
                {
                    time = 0;
                    int count = client.Socket.Receive(temp);
                    byte[] buff = new byte[count];
                    Array.Copy(temp, 0, buff, 0, count);

                    ClientNode node = Decode(buff);
                    if (node == null)
                        Common.log.Info("命令解析失败: " + HexBuff(buff));
                    else
                        Common.log.Info("From Server: " + node.ToText());
                    UpdateNode(client, node);
                }
                else
                {
                    time += 100;
                    if (time > 10000)
                    {
                        Offline(client);
                        Common.log.Info("[" + client.IP + "] 超过10s没有收到数据,关闭连接");
                    }
                }
            }
            catch (Exception ex)
            {
                Common.log.Error("ListenNet", ex);
            }


        }

        private byte[] Encode(ClientNode node)
        {
            List<string> arr = new List<string>
            {
                "name:\"" + node.Name + "\"",
                "mark:\"" + node.Mark + "\"",
                "rfid:\"" + node.RFID + "\"",
                "action:\"" + node.Action.ToString() + "\"",
                "level:\"" + node.Level.ToString() + "\""
            };
            string s = "{" + string.Join(",", arr) + "}";
            byte[] buff = Encoding.UTF8.GetBytes(s);
            return buff;
        }

        private ClientNode Decode(byte[] buff)
        {
            string json = Encoding.UTF8.GetString(buff);
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            Dictionary<string, object> dic = (Dictionary<string, object>)serializer.DeserializeObject(json);
            if (dic == null) return null;

            ClientNode node = new ClientNode();
            if (dic.TryGetValue("name", out object value))
                node.Name = value.ToString();
            if (dic.TryGetValue("mark", out value))
                node.Mark = value.ToString();
            if (dic.TryGetValue("rfid", out value))
                node.RFID = value.ToString();
            if (dic.TryGetValue("action", out value))
            {
                if (Enum.TryParse(value.ToString(), out ClientAction action))
                    node.Action = action;
            }
            if (dic.TryGetValue("level", out value))
            {
                if (Enum.TryParse(value.ToString(), out ClientLevel level))
                    node.Level = level;
            }
            return node;
        }

        private string HexBuff(byte[] buff)
        {
            string s = "";
            if (buff == null) return s;

            for (int i = 0; i < buff.Length; i++)
                s += buff[i].ToString("X2") + " ";
            return s;
        }

        private void UpdateNode(Client client, ClientNode node)
        {
            if (node == null) return;
            int idx = client.NodeName.FindIndex(s => s == node.Name);
            if (idx == -1) client.NodeName.Add(node.Name);

            idx = Common.nodeInfos.FindIndex(s => s.Name == node.Name);



            //int idx = Common.nodeInfo.FindIndex(s => s.Name == node.Name);
            //if (idx == -1)
            //{
            //    Common.log.Info(node.Name + " 不存在");
            //    return;
            //}

            //if (!Common.nodeInfo[idx].Online)
            //{
            //    Common.nodeInfo[idx].Online = true;
            //    NodeOnline?.Invoke(idx);
            //    NodeChanged?.Invoke(idx);
            //}

            //if (Common.nodeInfo[idx].Mark != node.Mark ||
            //    Common.nodeInfo[idx].Action != node.Action ||
            //    Common.nodeInfo[idx].Level != node.Level ||
            //    Common.nodeInfo[idx].RFID != node.RFID)
            //{
            //    Common.nodeInfo[idx].Mark = node.Mark;
            //    Common.nodeInfo[idx].Action = node.Action;
            //    Common.nodeInfo[idx].Level = node.Level;
            //    Common.nodeInfo[idx].RFID = node.RFID;
            //    Common.log.Info(node.Name + "更新 " + node.ToText());
            //    NodeChanged?.Invoke(idx);
            //}
        }

        private void Offline(Client client)
        {
            //client.Loop = false;
            //client.IsConn = false;
            //client.Socket.Close();

            //for (int i = 0; i < client.nodeName.Count; i++)
            //{
            //    int idx = AGVControl.Common.nodeInfo.FindIndex(s => s.Name == client.nodeName[i]);
            //    if (idx == -1) continue;
            //    AGVControl.Common.nodeInfo[idx].Offline();
            //    NodeChanged(idx);
            //    NodeOnline(idx);
            //}
            //client.nodeName.Clear();
        }

        private class Client
        {
            public string IP;
            public bool IsConn;
            public List<string> NodeName;
            public Socket Socket;
            public Timer ListenNet;

            public Client()
            {
                IP = "";
                IsConn = false;
                NodeName = new List<string>();
            }

            public void Clear()
            {
                IP = "";
                IsConn = false;
                NodeName.Clear();
                Socket.Close();
                ListenNet.Dispose();
            }
        }

    }
}