开发者

C# Deserialization Over TCP

I have now an issue with deserializing an object sent over TCP.

When deserializing, I get the following SerializationException (code below):

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

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

The objects are being serialized at runtime, so I don't think it's a versioning issue. I am new to streaming etc, so I may have missed something obvious.

I'd like to suggest what I think it could be, but I'm really stuck. :)

Thanks.


serializedObjectStream.Length is a long.

You're writing a 64-bit value to the network, but you're trying to read it as a 32-bit int.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜