【问题标题】:I am getting a "system.runtime.serialization.serializationexception" when using the binary formatter使用二进制格式化程序时,我收到“system.runtime.serialization.serializationexception”
【发布时间】:2020-09-26 09:53:20
【问题描述】:
private byte[] ToByteArray(Message msg)
    {
       if(msg == null)
        {
            return null;
        }
        BinaryFormatter bf = new BinaryFormatter();
        using(MemoryStream ms = new MemoryStream())
        {
            bf.Serialize(ms, msg);
            return ms.ToArray();
        }
    }
    private Message ToMessageObject(Byte[] bytes)
    {
        if(bytes == null)
        {
            return null;
        }
        BinaryFormatter bf = new BinaryFormatter();
        using (MemoryStream ms = new MemoryStream(bytes))
        {
            ms.Write(bytes, 0, bytes.Length);
            ms.Position = 0;
            Message msg = (Message)bf.Deserialize(ms);
            return msg;
        }
    }

我正在使用上述两种方法进行序列化和反序列化,但是在反序列化过程中不断抛出错误。

system.runtime.serialization.serializationexception: '解析完成之前遇到的流结束。'

我的消息类具有“Serializable”属性。 我注意到的一件事是当文本很小时,比如两个词,它可以很好地反序列化,但是当它包含很多字符时,接近 100,那就是我得到那个错误的时候。我一直在检查这个问题的其他解决方案()frome here and other places,但似乎没有一个对我有用。

【问题讨论】:

  • 输入的消息来自哪里?检查源消息的字节数,然后与接收的字节数进行比较。您正在尝试在收到所有数据之前解析数据。反序列化需要处理前的所有字节。
  • @jdweng,所以,我正在尝试实现一个通过 tcp 通信的客户端和服务器应用程序,因此消息来自另一个或相同的客户端实例。谢谢,我能够找出问题所在,我在服务器端将字节数组的大小设置为 256,所以大于 256 的所有内容都会引发错误。所以我想知道是否有任何方法可以动态判断正在发送的字节的长度
  • @JózefPodlecki,完全没有,但我已经解决了问题,我将字节数组的大小设置为一个常数,感谢您的帮助
  • 你可以为此写一个答案。不明显

标签: c# .net serialization deserialization memorystream


【解决方案1】:

从cmets中,我能够弄清楚问题是由字节数组的初始化引起的,

var responseStream = client.GetStream()
var bytes = new byte[1024];
if (responseStream.DataAvailable)
{
   await responseStream.ReadAsync(bytes, 0, bytes.Length);
   var responseMessage =ToMessageObject(bytes);
   messages.Add(responseMessage);
}

最初,我将字节数组长度设置为 256。每当我必须反序列化长度大于 256 的字节数组时都会引发错误。所以,我想知道从流中读取时是否可以使用动态数组.

【讨论】:

  • 为了事先读取正在传输的字节的大小,我使用了“tcpClient.ReceiveBufferSize”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-24
  • 2018-11-16
  • 1970-01-01
相关资源
最近更新 更多