/// <summary> /// 反序列化 /// </summary> /// <param name="iep"></param> /// <param name="content"></param> /// <returns></returns> public static NotifyContext Deserialize(IPEndPoint iep, string content) { var notify = new NotifyContext { MsgSender = new SenderInfo { Ip = iep.Address.ToString(), Port = iep.Port, SendTime = DateTime.Now } }; try { string[] contentArr = content.Split(new[] { ',' }); if (contentArr.Length < 3) { throw new ApplicationException("消息解析长度小于3,消息内容:" + content); } var msgType = (EnumMsgType)Convert.ToInt32(contentArr[0].Substring(contentArr[0].IndexOf('=') + 1)); string msgBody = contentArr[contentArr.Length - 1].Substring(contentArr[0].IndexOf('=') + 1); if (_serializeDic.ContainsKey(msgType)) { notify.Msg = _serializeDic[msgType].Deserialize(msgType, contentArr[1].Substring(contentArr[1].IndexOf('=') + 1), msgBody); Logger.WriteInfoFmt(Log.Deserialize, "消息类型:{0},消息内容:{1}", new object[] { msgType.ToString(), content }); } else { throw new ApplicationException(string.Format("未找到消息类型{0}的反序列化方法", msgType)); } } catch (Exception ex) { Logger.WriteError(Log.Deserialize, "消息反序列化时出现异常", ex); } return(notify); }
private void ReceiveUdpMsg(object data) { try { //传入Socket Socket udpSocket = (Socket)data; IPEndPoint iep = new IPEndPoint(IPAddress.Any, 0); EndPoint ep = (EndPoint)iep; byte[] buffer = new byte[1024]; while (true) { int recv = udpSocket.ReceiveFrom(buffer, ref ep); string blockStr = Encoding.UTF8.GetString(buffer, 0, recv); //反序列化得到NotifyContext NotifyContext context = MessageFactory.Deserialize((IPEndPoint)ep, blockStr); //根据MsgType将消息添加到相应的回调队列 List <NotifyHandler> handlers = _callbackDic[context.Msg.MsgTag.MsgType]; foreach (var notifyHandler in handlers) { _callbackQueue.Enqueue(new NotifyModel { ModelContext = context, ModelHandler = notifyHandler }); } } } catch (Exception ex) { Logger.WriteError(Log.ReceiveUdpMsg, "接收Udp消息时出现异常", ex); } }