/// <summary> /// 接收信息回调 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private static void Client_ReceivedDatagram(object sender, NetReceiveEventArgs e) { String datagram = e.Datagram; JsonSerializerSettings jsonSettings = new JsonSerializerSettings(); jsonSettings.Converters.Add(new REQConverter()); BaseREQ req = JsonConvert.DeserializeObject <BaseREQ>(datagram, jsonSettings); if (req == null) { return; } switch (req.t) { case REQ_TYPE.CONN_RESP: //连接响应 { if (req is ConnRESP && ((ConnRESP)req).status == CONN_RESP_TYPE.RESP_SUCCESS) { StartSendThread(); } } break; case REQ_TYPE.PUSH_ACK: //上传数据响应 { if (req is PushAck && ((PushAck)req).status == ResultStatus.Success) { PushAck ack = (PushAck)req; } } break; case REQ_TYPE.CMD_REQ: //命令请求 { if (req is CmdReq) { CmdReq cmd = req as CmdReq; if (cmd.data != null && cmd.data.ToString() != "") { //接收发过来的JSON格式命令,使用JsonConvert反序列 if (cmd.apitag == Cfg.jsonActuator) { Member user = JsonConvert.DeserializeObject <Member>(cmd.data.ToString()); Console.WriteLine("JSON格式命令:" + Environment.NewLine); Console.WriteLine(String.Format("{0}/{1}/{2}/{3}" , user.UserName , user.Age , user.Sex , user.IsMarry) + Environment.NewLine); } //接收发过来的二进制格式命令,使用Base64解码 else if (cmd.apitag == Cfg.binaryActuator) { Byte[] ary = Convert.FromBase64String(cmd.data.ToString()); Console.WriteLine("二进制格式命令:" + Environment.NewLine); Console.WriteLine(String.Format("{0}/{1}/{2}/{3}" , ary[0] , ary[1] , ary[2] , ary[3]) + Environment.NewLine); } } CmdResp resp = new CmdResp() { cmdid = cmd.cmdid, t = REQ_TYPE.CMD_RESP, status = (Byte)ResultStatus.Success }; client.SendText(Newtonsoft.Json.JsonConvert.SerializeObject(resp)); } } break; } }
/// <summary> /// ReadJson方法定义的是Json.Net用来处理反序列化的逻辑 /// </summary> public override object ReadJson(JsonReader reader, Type objectType, Object existingValue, JsonSerializer serializer) { BaseREQ result = null; JObject jObject = null; try { jObject = JObject.Load(reader); } catch { return(result); } REQ_TYPE t = REQ_TYPE.NONE; try { Enum.TryParse <REQ_TYPE>(jObject["t"] == null ? "" : jObject["t"].ToString(), out t); if (t == REQ_TYPE.NONE) { return(result); } switch (t) { case REQ_TYPE.CONN_RESP: { String strJson = JsonConvert.SerializeObject(jObject); result = JsonConvert.DeserializeObject <ConnRESP>(strJson); } break; case REQ_TYPE.PUSH_ACK: { String strJson = JsonConvert.SerializeObject(jObject); result = JsonConvert.DeserializeObject <PushAck>(strJson); } break; case REQ_TYPE.CMD_REQ: { String strJson = JsonConvert.SerializeObject(jObject); result = JsonConvert.DeserializeObject <CmdReq>(strJson); } break; } } finally { //以上的一些字段的类型解析错误会为空,则根据t初始BaseREQ类型 if (result == null) { result = new BaseREQ() { t = t } } ; } return(result); } }