gpt4 book ai didi

通过 TCP 的 C# 反序列化

转载 作者:可可西里 更新时间:2023-11-01 02:56:29 26 4
gpt4 key购买 nike

我现在遇到反序列化通过 TCP 发送的对象的问题。

反序列化时,我得到以下 SerializationException(下面的代码):

Additional information: Binary stream '0' does not contain a valid BinaryHeader. Possible causes are invalid stream or object version change between serialization and deserialization.

序列化代码:

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();
}

反序列化代码:

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;
}

对象在运行时被序列化,所以我认为这不是版本控制问题。我是流媒体等方面的新手,所以我可能错过了一些明显的东西。

我想提出我认为可能的建议,但我真的被困住了。 :)

谢谢。

最佳答案

serializedObjectStream.Length 是一个long

您正在向网络写入 64 位值,但您正试图将其作为 32 位 int 读取。

关于通过 TCP 的 C# 反序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7274176/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com