/// <summary> /// 初始化配置信息 /// </summary> public static void InitConfig(string logPath) { try { doc = new XmlDocument(); if (!System.IO.File.Exists(ConfigPath)) { return; } Type type = typeof(SysConfig); PropertyInfo[] Props = type.GetProperties(flags); PathMapAttribute PathMap = null; foreach (var prop in Props) { PathMap = GetMyAttribute<PathMapAttribute>(prop, false); if (PathMap != null) { prop.SetValue(null, Convert.ChangeType(GetConfigValue(PathMap), prop.PropertyType), null); } } WriteDeviceLog.WriteLog(logPath, $"配置服务初始化成功!",Guid.NewGuid().ToString()); } catch (Exception ex) { WriteDeviceLog.WriteLog(logPath, $"配置服务初始化错误,原因:{ex}!", Guid.NewGuid().ToString()); } }
/// <summary> /// 对象建立连接成功之后对扩展对象进行初始化 /// </summary> /// <param name="connId">连接对象</param> /// <param name="spreadObject">客户端附加参数</param> /// <param name="strAdvance">扩展参数</param> /// <param name="strCmd">回写命令</param> /// <param name="isDisconnect">是否重连</param> public void OnLinkStart(string connId, ref ConcurrentDictionary <string, SpreadModel> spreadObject, string strAdvance, ref byte[] strCmd, ref bool isDisconnect) { try { SpreadModel item = new SpreadModel(); if (connId != null) { item.connId = connId; item.AccessAddress = strAdvance; item.FirstTimeConnectTime = DateTime.Now; if (spreadObject.ContainsKey(connId)) { //更新客户端对象扩展信息 spreadObject[connId] = item; } else { //新增客户端扩展信息 spreadObject.TryAdd(connId, item); } byte[] 保留字段 = new byte[2092]; strCmd = CopyByte(保留字段, datas);//保留字段+文件列表 strCmd = ByteHelper.PackByte(strCmd, Command.UpdateTempList); WriteDeviceLog.WriteLog("Log\\" + _DeviceName + "\\解析日志", $@"发送更新列表{FileListFileInformation.Count}个 大小{strCmd.Length}字节", Guid.NewGuid().ToString()); } } catch (Exception e) { WriteDeviceLog.WriteLog("Log\\" + _DeviceName + "\\解析日志", $@"{strAdvance} {e}", Guid.NewGuid().ToString()); isDisconnect = true;//断开连接 } }
/// <summary> /// 通过异步方式调用的方式处理一些不太重要的工作。 /// </summary> /// <param name="action">指定要执行的操作。</param> /// <param name="traceName"></param> public static void InvokeAsync(Action action, string traceName = null) { if (performanceTracer >= 0) { if (string.IsNullOrWhiteSpace(traceName)) { var method = new StackTrace().GetFrames()[1].GetMethod(); traceName = string.Format("{0}.{1}", method.ReflectedType.FullName, method.Name); } Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); action.BeginInvoke(delegate { stopwatch.Stop(); if (stopwatch.Elapsed.TotalMilliseconds > performanceTracer) { if (!Debugger.IsAttached) { WriteDeviceLog.WriteLog("Log\\" + traceName, "性能问题(" + traceName + ")" + stopwatch.Elapsed.TotalMilliseconds + "ms"); } Debug.WriteLine("性能问题({0}),耗时{1}毫秒。", traceName, stopwatch.Elapsed.TotalMilliseconds); } }, null); } else { action.BeginInvoke(null, null); } }
/// <summary> /// 调用并且跟踪指定代码块的执行时间。 /// </summary> /// <param name="action"></param> /// <param name="traceName">跟踪名称。</param> /// <param name="enableThrow">指定是否允许抛出异常。</param> public static void Invoke(Action action, string traceName = null, bool enableThrow = true) { if (performanceTracer >= 0) { if (string.IsNullOrWhiteSpace(traceName)) { var method = new StackTrace().GetFrames()[1].GetMethod(); traceName = string.Format("{0}.{1}", method.ReflectedType.FullName, method.Name); } try { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); action(); stopwatch.Stop(); if (stopwatch.Elapsed.TotalMilliseconds > performanceTracer) { if (!Debugger.IsAttached) { WriteDeviceLog.WriteLog("Log\\" + traceName, "性能问题(" + traceName + ")" + stopwatch.Elapsed.TotalMilliseconds + "ms"); } Debug.WriteLine("性能问题({0}),耗时{1}毫秒。", traceName, stopwatch.Elapsed.TotalMilliseconds); } } catch (Exception ex) { if (enableThrow) { throw; } //LogHelper.HandleError(ex, traceName ?? ex.Message); WriteDeviceLog.WriteLog("Log\\" + traceName, ex.Message); } } else { try { action(); } catch (Exception ex) { if (enableThrow) { throw; } WriteDeviceLog.WriteLog("Log\\" + traceName, ex.Message); } } }
HandleResult OnReceive(IntPtr connId, int length) { //针对同一连接的数据它是同步的,针对不同连接才是异步执行。 //根据数据库中的配置参数来控制拆包解包规则。 try { if (IsUnpack == 0) { //不启用拆包 IntPtr recivebuffer = Marshal.AllocHGlobal(length); if (_server.Fetch(connId, recivebuffer, length) == FetchResult.Ok) { byte[] sendBytes = new byte[length]; Marshal.Copy(recivebuffer, sendBytes, 0, length); Marshal.FreeHGlobal(recivebuffer);//释放申请的内存空间 return(HandleDeviceMessage(sendBytes, length, connId)); } } else { int reallength = 0; int bytesRead = 0;//包大小 if (GetDataLength(connId, ref reallength)) { while (length >= reallength + HeadSize) { length = length - reallength - HeadSize; IntPtr recivebuffer = Marshal.AllocHGlobal(reallength + HeadSize); //Fetch从数据包中捞出数据,改变缓存数据大小 if (_server.Fetch(connId, recivebuffer, reallength + HeadSize) == FetchResult.Ok) { //上面可以加配置,来控制该设备是否启用线程池处理数据或是启用单线程处理。 //使用线程池不会出现length缓存区溢出的情况。 byte[] sendBytes = new byte[reallength + HeadSize]; bytesRead = sendBytes.Length; Marshal.Copy(recivebuffer, sendBytes, 0, bytesRead); Marshal.FreeHGlobal(recivebuffer);//释放申请的内存空间 //return HandleDeviceMessage(sendBytes, bytesRead, connId); var result = _smartThreadPool.QueueWorkItem(() => { return(HandleDeviceMessage(sendBytes, bytesRead, connId)); }); } GetDataLength(connId, ref reallength); } } } return(HandleResult.Ok); } catch (Exception e) { WriteDeviceLog.WriteLog("Log\\" + _name + "\\OnReceiveError", e.ToString(), Guid.NewGuid().ToString()); return(HandleResult.Error); } }
HandleResult OnShutdown() { InitConfig(DbType); //服务关闭了 WriteDeviceLog.WriteLog("Log\\" + _name + "\\Shutdown客户端", $@" > [OnShutdown] 端口:{_port} 设备ID:{StrDeviceId} 设备名称:{_name}", Guid.NewGuid().ToString()); //服务信息 InitServiceInfo(false); //InitMonitorService.AutoResetEvent.Set(); return(HandleResult.Ok); }
/// <summary> /// 设备解析数据标准接口 /// </summary> /// <param name="strSource">需要解析的数据流</param> /// <param name="strCmd">回写数据流</param> /// <param name="eventId">事件ID</param> /// <param name="isDisconnect">是否断开连接,True:断开 False:不断开</param> /// <param name="isMass">是否群发</param> /// <param name="strAdvance">扩展参数</param> /// <param name="connId">客户端Id</param> /// <param name="spreadObject">客户端附加参数</param> public void ParseResult(byte[] strSource, ref byte[] strCmd, string eventId, ref bool isDisconnect, ref bool isMass, ref string strAdvance, string connId, ref ConcurrentDictionary <string, SpreadModel> spreadObject, ref bool IsUpdater, ref byte[] 扩展参数) { try { IsUpdater = true; byte[] len = new byte[4]; Array.Copy(strSource, 2, len, 0, 4); int lens = BitConverter.ToInt32(len, 0); byte[] realDatas = new byte[lens]; //真实数据大小 //去掉包头 Array.Copy(strSource, 11, realDatas, 0, lens); FileInformation sendUpdateContents = new FileInformation(); 请求文件信息 updateList = MsgPackHelper <请求文件信息> .UnPack(realDatas); WriteDeviceLog.WriteLog("Log\\" + _DeviceName + "\\解析日志", $@"收到文件ID:{updateList.FileId}", Guid.NewGuid().ToString()); //sendUpdateContents = FileByteContents.Where(x => x.FileId==updateList).ToList().First();//获取文件id对应的文件 sendUpdateContents = FileListFileInformation.Where(x => x.FileId == updateList.FileId).ToList().First(); WriteDeviceLog.WriteLog("Log\\" + _DeviceName + "\\解析日志", $@"whereId:{sendUpdateContents.FileId}", Guid.NewGuid().ToString()); //包头7字节 //2048长度来存放文件路径 //剩下的放文件内容 byte[] filePath = new byte[2048]; byte[] basePath = Encoding.Default.GetBytes(sendUpdateContents.BaseFilePath);//文件路径 Array.Copy(basePath, 0, filePath, 0, basePath.Length); 扩展参数 = filePath; strAdvance = sendUpdateContents.FilePath + "|" + sendUpdateContents.FileId + "|" + updateList.文件读取开始位置 + "|" + updateList.文件读取长度; WriteDeviceLog.WriteLog("Log\\" + _DeviceName + "\\解析日志", $@"返回:{strAdvance}", Guid.NewGuid().ToString()); //strCmd = CopyByte(filePath,FileHelper.GetFileBytes(sendUpdateContents.FilePath)); //strCmd = ByteHelper.PackByte(strCmd, Command.UpdateDatasList);//封包 //WriteDeviceLog.WriteLog("Log\\" + _DeviceName + "\\解析日志", $@"发送文件ID:{updateList} 大小:{strCmd.Length}字节", Guid.NewGuid().ToString()); if (connId != null) { if (spreadObject.ContainsKey(connId)) { //更新客户端对象扩展信息 spreadObject[connId].connId = connId; spreadObject[connId].DeviceCode = "AutoUpdaterService"; spreadObject[connId].AccessAddress = strAdvance; spreadObject[connId].LastTimeHandleTime = DateTime.Now; spreadObject[connId].OnlineTime = TimeHelper.GetTimeLong(spreadObject[connId].FirstTimeConnectTime, DateTime.Now, 1); } } } catch (Exception ex) { WriteDeviceLog.WriteLog("Log\\" + _DeviceName + "\\解析日志", $@"{strAdvance} {ex}", eventId); } }
/// <summary> /// 设备初始化规则 /// </summary> /// <param name="strDevice"></param> /// <param name="dbType"></param> public void GetRules(string strDevice, string dbType, ref string param1) { _DeviceID = strDevice; _DeviceName = strDevice; //加载客户端缓存文件 var fileHelper = new FileHelper(); //测试手动获取文件位置 FileListFileInformation = fileHelper.GetAllFiles(new System.IO.DirectoryInfo($@"{_baseDir}\UpdateTempFile")); //FileByteContents = FileHelper.FileByteContentsList; datas = MsgPackHelper <List <FileInformation> > .Pack(FileListFileInformation); //datas = SerializableHelper.ObjectToBytes(FileListFileInformation); WriteDeviceLog.WriteLog("Log\\" + _DeviceName + "\\解析日志", $@"加载内存:文件列表{FileListFileInformation.Count}个", Guid.NewGuid().ToString()); }
private void Form1_Load(object sender, EventArgs e) { string errorMsg = string.Empty; InitTcpServer tcpService = new InitTcpServer(); tcpService.DbType = "AutoUpdaterService"; if (tcpService.Start(true, ref errorMsg)) { MessageBox.Show("更新服务启动成功!", "提示"); WriteDeviceLog.WriteLog("Log\\Log", "更新服务启动成功!", Guid.NewGuid().ToString()); } else { MessageBox.Show($"更新服务启动失败!原因:{errorMsg}", "提示"); WriteDeviceLog.WriteLog("Log\\Log", $"更新服务启动失败!原因:{errorMsg}", Guid.NewGuid().ToString()); } }
private HandleResult ClosePool(IntPtr connId, SocketOperation enOperation, int errorCode) { try { ClientInfo clientInfo = _server.GetExtra(connId); string.Format(" > [{0},OnAccept] -> PASS({1}:{2})", connId, clientInfo.IpAddress, clientInfo.Port); if (errorCode == 0) { WriteDeviceLog.WriteLog("Log\\" + _name + "\\Close客户端", string.Format(" > [{0},OnClose] -> On({1}:{2})", connId, clientInfo.IpAddress, clientInfo.Port), Guid.NewGuid().ToString()); } else { WriteDeviceLog.WriteLog("Log\\" + _name + "\\Close客户端", string.Format(" > [{0},OnError] -> OP:{1},CODE:{2} -> On({3}:{4})", connId, enOperation, errorCode, clientInfo.IpAddress, clientInfo.Port), Guid.NewGuid().ToString()); } if (_server.RemoveExtra(connId) == false) { WriteDeviceLog.WriteLog("Log\\" + _name + "\\Close客户端", string.Format(" > [{0},OnClose] -> SetConnectionExtra({0}, null) fail -> On({1}:{2})", connId, clientInfo.IpAddress, clientInfo.Port), Guid.NewGuid().ToString()); } //连接断开删除客户端对象 string dicConnIdValue; DicConnId.TryRemove(connId.ToString(), out dicConnIdValue); SpreadModel value = null; SpreadObject.TryRemove(connId.ToString(), out value); //服务信息 InitServiceInfo(true); return(HandleResult.Ok); } catch (Exception ex) { WriteDeviceLog.WriteLog("Log\\" + _name + "\\Close客户端", ex.ToString(), Guid.NewGuid().ToString()); return(HandleResult.Error); } finally { //InitMonitorService.AutoResetEvent.Set(); } }
/// <summary> /// 跟踪指定代码块的执行时间。 /// </summary> /// <typeparam name="TResult"></typeparam> /// <param name="func"></param> /// <param name="traceName">跟踪名称。</param> /// <returns>返回类型为<typeparamref name="TResult"/>的结果。</returns> public static TResult Invoke <TResult>(Func <TResult> func, string traceName = null) { if (performanceTracer >= 0) { if (string.IsNullOrWhiteSpace(traceName)) { var method = new StackTrace().GetFrames()[1].GetMethod(); traceName = string.Format("{0}.{1}", method.ReflectedType.FullName, method.Name); } Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); TResult result = func(); stopwatch.Stop(); if (stopwatch.Elapsed.TotalMilliseconds > performanceTracer) { if (!Debugger.IsAttached) { WriteDeviceLog.WriteLog("Log\\" + traceName, "性能问题(" + traceName + ")" + stopwatch.Elapsed.TotalMilliseconds + "ms"); } Debug.WriteLine("性能问题({0}),耗时{1}毫秒。", traceName, stopwatch.Elapsed.TotalMilliseconds); } return(result); } else { return(func()); } }
private HandleResult HandleDeviceMessage(byte[] handleData, int bytesRead, IntPtr connId) { lock (_lock) { try { bool IsUpdater = false; string strAdvance = string.Empty; byte[] strCmd = new byte[0]; byte[] 扩展参数 = new byte[0]; bool IsDisconnect = false; //是否强制断开客户端 bool IsMass = false; //是否群发 IntPtr connIDKey; ClientInfo clientInfo = _server.GetExtra(connId); //extra.Get(connId); if (clientInfo != null) { strAdvance = $@" > [{clientInfo.ConnId},OnReceive] -> {clientInfo.IpAddress}:{clientInfo.Port} ({ bytesRead } bytes)"; } else { strAdvance = $@" > [{connId},OnReceive] -> ({bytesRead} bytes)"; } if (Dic.ContainsKey(StrDeviceId)) { string EventID = Guid.NewGuid().ToString(); IResolve = Dic[StrDeviceId]; IResolve.ParseResult(handleData, ref strCmd, EventID, ref IsDisconnect, ref IsMass, ref strAdvance, connId.ToString(), ref SpreadObject, ref IsUpdater, ref 扩展参数); //是否是更新服务 if (IsUpdater) { byte[] data = new byte[0]; FileStream fs = null; //获得文件所在路径 string filePath = strAdvance.Split('|')[0].Trim(); string 文件Id = strAdvance.Split('|')[1].Trim(); long 文件读取开始位置 = long.Parse(strAdvance.Split('|')[2].Trim()); long 文件读取长度 = long.Parse(strAdvance.Split('|')[3].Trim()); byte[] 文件IdBytes = Encoding.Default.GetBytes(文件Id);//36字节 //打开文件 try { fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); fs.Position = 文件读取开始位置; //设置开始读取位置 byte[] bytes = new byte[文件读取长度]; fs.Read(bytes, 0, (int)文件读取长度); //读取指定位置的数据 byte[] tempData = new byte[0]; byte[] 文件总长bytes = new byte[8]; 文件总长bytes = BitConverter.GetBytes(文件读取长度); tempData = CopyByte(扩展参数, 文件IdBytes); //文件路径+文件id tempData = CopyByte(tempData, 文件总长bytes); //+文件总长度 tempData = CopyByte(tempData, bytes); //文件路径+文件id tempData = ByteHelper.PackByte(tempData, Command.UpdateDatasList); //封包 //向connId发送命令 if (_server.Send(connId, tempData, tempData.Length) == false) { WriteDeviceLog.WriteLog("Log\\" + _name + "\\ResponseError应答", strAdvance + " 应答没有发出去。", Guid.NewGuid().ToString()); } else { WriteDeviceLog.WriteLog("Log\\" + StrDeviceId + "\\解析日志", $@"{DateTime.Now}:发送包大小{tempData.Length},路径:{filePath}" + "\r\n", Guid.NewGuid().ToString()); //WriteDeviceLog.WriteLog("Log\\" + _name + "\\更新日志", // $"发送包大小{tempData.Length}", // Guid.NewGuid().ToString()); } fs.Close(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } //尚未读取的文件内容长度 //long left = fs.Length; //long 文件总长 = left; //byte[] 文件总长bytes=new byte[8]; //文件总长bytes = BitConverter.GetBytes(文件总长); ////存储读取结果 //byte[] bytes = new byte[10 * 1024 * 1024];//10MB每秒 // //每次读取长度 //int maxLength = bytes.Length; ////读取位置 //long start = 0; ////实际返回结果长度 //int num = 0; //if (left == 0) //{ // 发包数量++; // //如果是空文件 // bytes = new byte[left]; // num = fs.Read(bytes, 0, Convert.ToInt32(left)); // byte[] tempData =new byte[0]; // tempData = CopyByte(扩展参数, 文件IdBytes);//文件路径+文件id // tempData = CopyByte(tempData, 文件总长bytes);//+文件总长度 // tempData = CopyByte(tempData, bytes);//文件路径+文件id // tempData = ByteHelper.PackByte(tempData, Command.UpdateDatasList);//封包 // //向connId发送命令 // if (_server.Send(connId, tempData, tempData.Length) == false) // { // WriteDeviceLog.WriteLog("Log\\" + _name + "\\ResponseError应答", // strAdvance + " 应答没有发出去。", // Guid.NewGuid().ToString()); // } // else // { // WriteDeviceLog.WriteText(AppDomain.CurrentDomain.BaseDirectory + "Log\\更新日志.txt", $@"{DateTime.Now}:发包数量:{发包数量},发送包大小{tempData.Length},路径:{filePath}" + "\r\n"); // //WriteDeviceLog.WriteLog("Log\\" + _name + "\\更新日志", // // $"发送包大小{tempData.Length}", // // Guid.NewGuid().ToString()); // } //} ////当文件未读取长度大于0时,不断进行读取 //while (left > 0) //{ // fs.Position = start; // num = 0; // if (left < maxLength) // { // bytes = new byte[left]; // num = fs.Read(bytes, 0, Convert.ToInt32(left)); // } // else // { // num = fs.Read(bytes, 0, maxLength); // } // Console.WriteLine($"文件原始长度{bytes.Length} 总长度{data.Length}"); // byte[] tempData = new byte[0]; // tempData = CopyByte(扩展参数, 文件IdBytes);//文件路径+文件id // tempData = CopyByte(tempData, 文件总长bytes);//+文件总长度 // tempData = CopyByte(tempData, bytes);//文件路径+文件id // tempData = ByteHelper.PackByte(tempData, Command.UpdateDatasList);//封包 // //向connId发送命令 // if (_server.Send(connId, tempData, tempData.Length) == false) // { // WriteDeviceLog.WriteLog("Log\\" + _name + "\\ResponseError应答", // strAdvance + " 应答没有发出去。", // Guid.NewGuid().ToString()); // } // else // { // 发包数量++; // WriteDeviceLog.WriteText(AppDomain.CurrentDomain.BaseDirectory + "Log\\更新日志.txt", $@"{DateTime.Now}:发包数量:{发包数量},发送包大小{tempData.Length},路径:{filePath}" + "\r\n"); // //WriteDeviceLog.WriteLog("Log\\" + _name + "\\更新日志", // // $"发送包大小{tempData.Length}", // // Guid.NewGuid().ToString()); // } // Console.WriteLine($"包头+长度+文件内容长度{tempData.Length}"); // if (num == 0) // break; // start += num; // left -= num; // //Thread.Sleep(888); //} //fs.Close(); } //是否强制断开连接True:强制断开客户端 False 不执行断开操作 if (IsDisconnect) { return(HandleResult.Error); } //是否群发命令 True:群发命令 False:不群发 if (IsMass) { //启用群发命令 if (strCmd.Length > 0) { if (DicConnId != null) { foreach (KeyValuePair <string, string> kvp in DicConnId) { connIDKey = (IntPtr)int.Parse(kvp.Key); if (kvp.Value.Contains(StrDeviceId)) { if (_server.Send((IntPtr)int.Parse(kvp.Key), strCmd, strCmd.Length) == false) //拿到kvp.Key客户端对象 { WriteDeviceLog.WriteLog("Log\\" + _name + "\\ResponseError应答", strAdvance + $" 应答没有发出去。发送对象:{_server.GetExtra((IntPtr)int.Parse(kvp.Key)).IpAddress}:{_server.GetExtra((IntPtr)int.Parse(kvp.Key)).Port} strCmd:" + Encoding.Default.GetString(strCmd), Guid.NewGuid().ToString()); } } } } } } else { if (strCmd.Length > 0) { if (_server.Send(connId, strCmd, strCmd.Length) == false) //拿到kvp.Key客户端对象 { WriteDeviceLog.WriteLog("Log\\" + _name + "\\ResponseError应答", strAdvance + $" 应答没有发出去。strCmd:" + Encoding.Default.GetString(strCmd), Guid.NewGuid().ToString()); } } } //是否一直保持连接,True:服务端一直连着客户端,False:服务端解析完成客户端的数据断开客户端。 if (IResolve.IsContinueConnecting() == false) { return(HandleResult.Error); } } return(HandleResult.Ok); } catch (Exception e) { WriteDeviceLog.WriteLog("Log\\" + _name + "\\HandleDeviceMessageError", e.ToString(), Guid.NewGuid().ToString()); return(HandleResult.Error); } } }
private HandleResult AcceptPool(IntPtr connId) { try { string strAdvance = string.Empty; byte[] strCmd = new byte[0]; bool IsDisconnect = false; //是否强制断开客户端 string ip = string.Empty; ushort sport = 0; if (_server.GetRemoteAddress(connId, ref ip, ref sport)) { strAdvance = string.Format(" > [{0},OnAccept] -> PASS({1}:{2})", connId, ip.ToString(), sport); WriteDeviceLog.WriteLog("Log\\" + _name + "\\Accept客户端", strAdvance, Guid.NewGuid().ToString()); } else { strAdvance = string.Format(" > [{0},OnAccept] -> Server_GetClientAddress() Error", connId); WriteDeviceLog.WriteLog("Log\\" + _name + "\\Accept客户端", strAdvance, Guid.NewGuid().ToString()); } ClientInfo clientInfo = new ClientInfo(); clientInfo.ConnId = connId; clientInfo.IpAddress = ip; clientInfo.Port = sport; if (_server.SetExtra(connId, clientInfo) == false) { //给客户端连接加载连接参数失败,处理出错。 } //连接断开时要干掉客户端对象。不然会增长过大。 if (DicConnId.ContainsKey(connId.ToString())) { DicConnId[connId.ToString()] = StrDeviceId; } else { DicConnId.TryAdd(connId.ToString(), StrDeviceId); //客户端连接池 } //if (SpreadObject.ContainsKey(connId)) //{ // SpreadObject[connId] = new SpreadModel(); //} //else //{ // SpreadObject.TryAdd(connId, new SpreadModel());//客户端扩展对象池 //} Thread.Sleep(1500); if (Dic.ContainsKey(StrDeviceId)) { IResolve = Dic[StrDeviceId]; IResolve.OnLinkStart(connId.ToString(), ref SpreadObject, strAdvance, ref strCmd, ref IsDisconnect); //是否强制断开连接True:强制断开客户端 False 不执行断开操作 if (IsDisconnect) { return(HandleResult.Error); } if (strCmd.Length > 0) { if (_server.Send(connId, strCmd, strCmd.Length) == false) { WriteDeviceLog.WriteLog("Log\\" + _name + "\\OnConnect", " 应答没有发出去。strCmd:" + Encoding.Default.GetString(strCmd), Guid.NewGuid().ToString()); } } } InitServiceInfo(true); return(HandleResult.Ok); } catch (Exception ex) { WriteDeviceLog.WriteLog("Log\\" + _name + "\\Accept客户端", ex.ToString(), Guid.NewGuid().ToString()); return(HandleResult.Error); } finally { //InitMonitorService.AutoResetEvent.Set(); } }