我现在遇到了通过TCP反序列化对象的问题 .
反序列化时,我得到以下SerializationException(下面的代码):
附加信息:二进制流'0'不包含有效的BinaryHeader . 可能的原因是序列化和反序列化之间的无效流或对象版本更改 .
Serialization code:
public static void SerializeRO(Stream stream, ReplicableObject ro) {
MemoryStream serializedObjectStream = new MemoryStream();
Formatter.Serialize(serializedObjectStream, ro);
BinaryWriter bw = new BinaryWriter(stream);
bw.Write(serializedObjectStream.Length);
serializedObjectStream.WriteTo(stream);
serializedObjectStream.Close();
bw.Close();
}
Deserialization code:
public static List<ReplicableObject> ParseStreamForObjects(Stream stream) {
List<ReplicableObject> result = new List<ReplicableObject>();
while (true) {
if (!(stream as NetworkStream).DataAvailable) break;
BinaryReader br = new BinaryReader(stream);
int length = br.ReadInt32();
byte[] bytes = br.ReadBytes(length);
MemoryStream ms = new MemoryStream(bytes);
ms.Position = 0;
// ERROR OCCURS ON THE LINE BELOW
result.Add((ReplicableObject) Formatter.Deserialize(ms));
ms.Close();
br.Close();
}
return result;
}
这些对象在运行时被序列化,所以我认为这不是版本问题 . 我是流媒体新手等,所以我可能错过了一些明显的东西 .
我想建议我认为它可能是什么,但我真的被卡住了 . :)
谢谢 .
1 回答
serializedObjectStream.Length
是long
.你're writing a 64-bit value to the network, but you'试图将其读作32位
int
.