private void client_ClientClosed(UpdateClient_2G obj)
 {
     if (listClient.Contains(obj))
     {
         listClient.Remove(obj);
     }
 }
        private void run()
        {
            try
            {
                byte[] buf = new byte[_recBufferSize];
                while (true)
                {
                    int count = client.Receive(buf);
                    if (count == 0) //远程主机关闭了连接
                    {
                        client.Close();
                        OnClientClosed("下载断开");
                        return;
                    }
                    else
                    {
                        string str = Encoding.ASCII.GetString(buf, 0, count);

                        if (str.StartsWith("$UPD"))   //确认是升级串
                        {
                            str = str.Split('\0')[0]; //去除重复数据
                            string[] array = str.Split('*');
                            if (array.Length > 1)     //正确串
                            {
                                string upStr  = array[0];
                                string sumStr = array[1];
                                string csstr  = Common.GetCheckSumString(upStr);
                                if (csstr == sumStr)            //检验和正确
                                {
                                    upStr = upStr.Remove(0, 4); //移除前缀
                                    if (upStr.StartsWith("DLREQ"))
                                    {
                                        var tmpArray = upStr.Split(',');
                                        if (tmpArray.Length == 6)
                                        {
                                            if (tmpArray[1] == "U@d8k%4#jD" && Common.IsNumricForNum(tmpArray[2]) && Common.IsNumricForNum(tmpArray[3]) && Common.IsNumricForNum(tmpArray[4]))
                                            {
                                                mac = tmpArray[5];
                                                if (_server_2G.listClient.Any(x => x.mac == mac && x != this))
                                                {   //存在相同的连接
                                                    UpdateClient_2G sameClient = _server_2G.listClient.First(x => x.mac == mac && x != this);
                                                    try
                                                    {
                                                        if (sameClient.thread != null)
                                                        {
                                                            sameClient.thread.Abort();
                                                        }
                                                    }
                                                    catch { }
                                                    sameClient.OnClientClosed(null);
                                                }

                                                if (updateInfo == null || !updateInfo.AutoUpdate || !updateInfo.needUpdate)
                                                {
                                                    client.Close();
                                                    OnClientClosed(null);
                                                    return;
                                                }

                                                int upVer = Convert.ToInt32(tmpArray[2]);
                                                if (main.upVer == upVer || main.upVer + 1 == upVer) //升级版本一致
                                                {
                                                    int offset = Convert.ToInt32(tmpArray[3]);
                                                    int size   = ConfigHelper.GetConfigInt("UpPkgSize", -1);
                                                    if (size == -1)
                                                    {
                                                        size = Convert.ToInt32(tmpArray[4]);
                                                    }
                                                    if (size <= 0)
                                                    {
                                                        size = 480;
                                                    }

                                                    int readLen = main.fileStream.Length - offset;
                                                    if (readLen > size)
                                                    {
                                                        readLen = size;
                                                    }
                                                    double rspOffset     = offset + readLen;
                                                    byte[] readFileBytes =
                                                        main.fileStream
                                                        .Where((b, index) => index >= offset && index < rspOffset)
                                                        .ToArray();
                                                    int    rspSize  = readLen + 80;
                                                    byte[] rspBytes = new byte[rspSize];
                                                    uint   crc      = CRC.crc_32_calc(readFileBytes, (UInt16)(readLen * 8),
                                                                                      0);
                                                    string header      = $"$UPDDLACK,{upVer},{offset},{readLen},";
                                                    byte[] headerBytes = Encoding.ASCII.GetBytes(header);
                                                    int    nlen        = headerBytes.Length;
                                                    Array.Copy(headerBytes, rspBytes, nlen);
                                                    Array.Copy(readFileBytes, 0, rspBytes, nlen, readLen);
                                                    nlen += readLen;
                                                    string crcStr   = crc.ToString("X8") + "\n";
                                                    byte[] crcBytes = Encoding.ASCII.GetBytes(crcStr);
                                                    Array.Copy(crcBytes, 0, rspBytes, nlen, crcBytes.Length);
                                                    nlen += crcBytes.Length;
                                                    byte   cs       = Common.CheckSumBytes(rspBytes, nlen);
                                                    string cumStr   = "*" + (((uint)cs) & 0xFF).ToString("X2");
                                                    byte[] cumBytes = Encoding.ASCII.GetBytes(cumStr);
                                                    Array.Copy(cumBytes, 0, rspBytes, nlen, cumBytes.Length);
                                                    nlen += cumBytes.Length;

                                                    //未启动升级 或者 无需升级 或者 暂停升级 跳过升级
                                                    if (updateInfo.PauseUpdate)
                                                    {
                                                        pauseBytes = rspBytes.Take(nlen).ToArray();
                                                        continue;
                                                    }
                                                    pauseBytes = null;

                                                    client.Send(rspBytes, nlen, SocketFlags.None);

                                                    if (main.ProgressMode == "P")
                                                    {
                                                        updateInfo.sended = string.Format("{1} ({0:P2})",
                                                                                          rspOffset / main.fileStream.Length,
                                                                                          main.fileStream.Length - rspOffset);
                                                    }
                                                    else if (main.ProgressMode == "T")
                                                    {
                                                        updateInfo.sended = (main.fileStream.Length - rspOffset).ToString();
                                                    }

                                                    if (rspOffset >= main.fileStream.Length)
                                                    {
                                                        updateInfo.DevStatus = DevStatus.DownloadRomSuccess;
                                                    }

                                                    updateInfo.lastUpdSendTime = DateTime.Now;
                                                }
                                                else
                                                {
                                                    updateInfo.sended    = "版本不一致";
                                                    updateInfo.DevStatus = DevStatus.DownloadRomError;
                                                }
                                            }
                                        }
                                    }
                                    else if (upStr.StartsWith("REG"))
                                    {
                                    }
                                    else if (upStr.StartsWith("UPDACK"))
                                    {
                                        var tmpArray = upStr.Split(',');
                                        if (tmpArray.Length == 3)
                                        {
                                            mac = tmpArray[1];
                                        }

                                        if (updateInfo != null)
                                        {
                                            if (pauseBytes == null)
                                            {
                                                updateInfo.sended = "升级启动...";
                                            }
                                            else
                                            {
                                                client.Send(pauseBytes, SocketFlags.None);
                                            }
                                            updateInfo.lastUpdSendTime = DateTime.Now;
                                        }
                                    }
                                    else
                                    {
                                    }
                                }
                            }
                        }
                        else
                        {
                            client.Send(buf);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (ex is SocketException)
                {
                    OnClientClosed("下载断开");
                }
                else
                {
                    if (!(ex is ThreadAbortException))
                    {
                        LogHelper.WriteError(ex, "UpdateClient_2G");
                    }
                }
                try
                {
                    client?.Close();
                }
                catch
                {
                }
                //MessageBox.Show(ex.Message);
            }
        }
        public void Start(Delegate startSuccessCallBack)
        {
            if (thread != null && thread.IsAlive)
            {
                return;
            }

            thread = new Thread(() =>
            {
                IPAddress ip;
                if (IPAddress.TryParse(main.serverIP, out ip))
                {
                    try
                    {
                        IPEndPoint ipep = new IPEndPoint(IPAddress.Any, main.updatePort); //4518
                        server          = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                        server.Bind(ipep);
                        server.Listen(10);
                        listening = true;
                        startSuccessCallBack?.DynamicInvoke();
                        while (listening)
                        {
                            try
                            {
                                Socket sok = server.Accept();
                                if (OnlineClients > MaxClient)
                                {
                                    sok.Close(); //连接数过多 阻止
                                }
                                else
                                {
                                    UpdateClient_2G client = new UpdateClient_2G(this, sok, main);
                                    client.ClientClosed   += client_ClientClosed;
                                    listClient.Add(client);
                                    client.Start();
                                }
                            }
                            catch (Exception ex)
                            {
                                if (ex is SocketException || ex is ObjectDisposedException)
                                {
                                }
                                else
                                {
                                    LogHelper.WriteError(ex, "UpdateServer_2G");
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        listening = false;
                        main.Dispatcher.BeginInvoke(new Action(() =>
                        {
                            MessageBox.Show(this.main, "升级服务启动失败,请检查端口是否被占用!\r\n错误消息:" + ex.Message, "提示",
                                            MessageBoxButton.OK, MessageBoxImage.Error);
                        }), null);
                    }
                }
                else
                {
                    listening = false;
                    main.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        MessageBox.Show(this.main, "升级服务器IP地址不正确,启动失败!", "提示", MessageBoxButton.OK,
                                        MessageBoxImage.Stop);
                    }), null);
                }
                listening = false;
            });
            thread.Name         = "UpdateServer_2G";
            thread.IsBackground = true;
            thread.Start();
        }