二进制流'0'不包含有效的BinaryHeader

本文关键字:有效 BinaryHeader 包含 二进制 | 更新日期: 2023-09-27 18:01:44

我有服务器和客户端应用程序,它们通过NetworkStream进行通信。在服务器上,I二进制序列化对象并通过NetworkStream发送,它在客户端上读取并反序列化。但它抛出和错误:二进制流'0'不包含有效的BinaryHeader。可能的原因是序列化和反序列化之间无效的流或对象版本更改。首先,我检查了NetworkStream的长度,在发送序列化对象后,它在服务器和客户端上是相同的。然后我添加一个服务器引用到客户端,并使用服务器。SaveData以确保在反序列化时具有完全相同的类。

然后我尝试在服务器上序列化和反序列化同一个对象,下面的代码工作得很好。

stream.Read(buffer, 0, total);
network_stream.Write(buffer, 0, total);
network_stream.Read(buffer, 0, total);
stream.Position = 0;
stream.Write(buffer, 0, total);
SaveData savedata = (SaveData)formatter.Deserialize(stream);

这是来自服务器的完整代码:

Stream stream = new MemoryStream();
IFormatter formatter = new BinaryFormatter();
current_state.saveData(map, red, blu);
formatter.Serialize(stream, current_state);
int total = (int)stream.Length;
byte[] buffer = new byte[total];
writer.WriteLine(total.ToString());
writer.Flush();
stream.Read(buffer, 0, total);
network_stream.Write(buffer, 0, total);
stream.Close();

客户端:

Stream stream = new MemoryStream();
IFormatter formatter = new BinaryFormatter();
while (reader.Peek() == ''0') { reader.Read(); } //solved the problem, idkw
int total = Convert.ToInt32(reader.ReadLine().ToString());
byte[] buffer = new byte[total];
network_stream.Read(buffer, 0, total);
stream.Position = 0;
stream.Write(buffer, 0, total);
stream.Position = 0;
Console.Write(stream.Length.ToString());
Server.SaveData current_state = (Server.SaveData)formatter.Deserialize(stream); //here is the problem
stream.Close();

二进制流'0'不包含有效的BinaryHeader

为什么不直接将数据序列化/反序列化到NetworkStream(不需要中间的MemoryStream)?

一个小例子。

假设有一个服务器和客户端用来交换的数据结构(在你的例子中,数据结构是current_state)

[Serializable]
public class UserData : ISerializable
{
    public string Text { get; private set; }
    public int Number { get; private set; }
    public UserData(string text, int number)
    {
        Text = text;
        Number = number;
    }
    protected UserData(SerializationInfo info, StreamingContext context)
    {
        Text = info.GetString("Text");
        Number = info.GetInt32("Number");
    }
    void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
    {
        info.AddValue("Text", Text);
        info.AddValue("Number", Number);
    }
}

发送数据结构(例如从客户端):

using (var networkStream = tcpClient.GetStream())
{
    var userData = new UserData("Hello.", 9);
    var binaryFormatter = new BinaryFormatter();
    binaryFormatter.Serialize(networkStream, userData);
}

接收数据结构(例如服务器端):

var binaryFormatter = new BinaryFormatter();
using (var networkStream = tcpClient.GetStream())
{
    while (networkStream.DataAvailable)
    {
        var receivedData = (UserData)binaryFormatter.Deserialize(networkStream);
    }
}