private void AsyncCallback(IAsyncResult ar) { if (ar.AsyncState is AsyncStateOne state) { try { int received = state.WorkSocket.EndReceiveFrom(ar, ref state.UdpEndPoint); //释放连接关联 state.WorkSocket = null; //马上开始重新接收,提供性能保障 RefreshReceive(); //处理数据 if (received >= HslCommunicationCode.HeadByteLength) { //检测令牌 if (NetSupport.IsTwoBytesEquel(state.BytesContent, 12, KeyToken.ToByteArray(), 0, 16)) { state.IpEndPoint = (IPEndPoint)state.UdpEndPoint; int contentLength = BitConverter.ToInt32(state.BytesContent, HslCommunicationCode.HeadByteLength - 4); if (contentLength == received - HslCommunicationCode.HeadByteLength) { byte[] head = new byte[HslCommunicationCode.HeadByteLength]; byte[] content = new byte[contentLength]; Array.Copy(state.BytesContent, 0, head, 0, HslCommunicationCode.HeadByteLength); if (contentLength > 0) { Array.Copy(state.BytesContent, 32, content, 0, contentLength); } //解析内容 content = NetSupport.CommandAnalysis(head, content); int protocol = BitConverter.ToInt32(head, 0); int customer = BitConverter.ToInt32(head, 4); //丢给数据中心处理 DataProcessingCenter(state, protocol, customer, content); } else { //否则记录到日志 LogNet?.WriteWarn(LogHeaderText, $"接收到异常数据,应接收长度:{(BitConverter.ToInt32(state.BytesContent, 4) + 8)} 实际接收:{received}"); } } else { LogNet?.WriteWarn(LogHeaderText, StringResources.TokenCheckFailed); } } else { LogNet?.WriteWarn(LogHeaderText, $"接收到异常数据,长度不符合要求,实际接收:{received}"); } } catch (ObjectDisposedException ex) { //主程序退出的时候触发 } catch (Exception ex) { LogNet?.WriteException(LogHeaderText, StringResources.SocketEndReceiveException, ex); //重新接收,此处已经排除掉了对象释放的异常 RefreshReceive(); } finally { //state = null; } } }