/// <summary> /// 反序列化包裹(快递) /// </summary> public static BeePacket DecodePacket(byte[] data) { using (var ms = new MemoryStream(data)) { using (var br = new BinaryReader(ms)) { var msg = new BeePacket(); msg.OpCode = br.ReadInt32(); msg.SubCode = br.ReadInt32(); //FIXME 有必要判断?类型待商榷 var count = (int)(ms.Length - ms.Position); if (count > 0) { var valueBytes = br.ReadBytes(count); msg.Message = DecodeMessage(valueBytes); } else { msg.Message = null; } return(msg); } } }
/// <summary> /// 序列化包裹 /// </summary> public static byte[] EncodePacket(BeePacket packet) { using (var ms = new MemoryStream()) { using (var bw = new BinaryWriter(ms)) { bw.Write(packet.OpCode); bw.Write(packet.SubCode); if (packet.Message != null) { // todo 这里object类型转换为接口 var valueBytes = EncodeMessage(packet.Message); bw.Write(valueBytes); } var data = new byte[ms.Length]; Buffer.BlockCopy(ms.GetBuffer(), 0, data, 0, (int)ms.Length); return(data); } } }