c# - BinaryFormatter 异常

标签 c# .net exception serialization binaryformatter

我正在尝试将对象图从服务器进程移动到客户端。它有效。至少当客户端和服务器都在我的开发虚拟机上时它可以工作。当我在我的基础机器(dev vm 上的客户端)上运行服务器时,它也可以工作。

不过,当我在我的媒体中心 PC 上运行服务器时,它停止工作了。异常(exception)情况是:

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

所有三台 PC 都是 x64 Windows 7 机器。我使用 TCPClient 和 TCPListener 以及 BinaryFormatter 类来完成繁重的工作。

正在传输的数据是使用标准 FileStream 对象从文件中读取的。

如果在客户端我将缓冲区序列化为一个文件,内容(根据 BeyondCompare)实际上似乎有所不同?!?

我的对象上的所有字符串属性都在 setter 中进行了 Base64 编码,并在 getter 中进行了解码。

我可以发布代码,但我不确定问题出在哪里?有什么想法吗?

最佳答案

更新:我似乎已经解决了这个问题。我有一个客户端读取服务器响应的断点

tcpClient.GetStream().Read(buffer, 0, buffer.Length);

并注意到从“问题”服务器读取的字节数较少。快速谷歌后,我找到了这篇文章 http://social.msdn.microsoft.com/Forums/en-US/ncl/thread/759f3f2f-347b-4bd8-aa05-fb7f681c3426 Dave Murray 在其中建议:

There are a couple ways to handle this more elegantly. If you're not planning on reusing the connection for anything else, the easiest is what nobugz suggests. When the server is done sending data, have it Close() it's end of the connection. When the client has read all data sent before the Close, Read will start returning 0, at which point you know the server isn't planning on sending anything else.

所以我将我的代码从一次读取更新为:

var buffer = new byte[32768];
var totalBytesRead = 0;
var bytesRead = tcpClient.GetStream().Read(buffer, 0, buffer.Length);

do
{
      totalBytesRead += bytesRead;
      bytesRead = tcpClient.GetStream().Read(buffer, totalBytesRead, bytesRead);

} while (bytesRead > 0);

并根据帖子更新了我的服务器代码以关闭连接。根据@leppie 的评论,我可能会删除我的 Base64 包装属性...

关于c# - BinaryFormatter 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5609892/

相关文章:

c# - 命令行参数参数限制

c# - 如何在C#中使用多语言

C# MongoDB 设置 ReadPreference

.net - .NET 序列化的版本兼容性?

c# - 对 lambda 表达式和委托(delegate)感到困惑?

java - 使用 HttpUrlConnection 获取 java.io.EOFException

python - 将关键字参数传递给自定义异常 - 异常

C# - 从第三方库导入类并使其成为派生类(或类似的类)

.net - 我是否应该始终对函数中返回的 LINQ 查询结果调用 .ToArray?

Java netty io/netty/channel/EventLoopGroup 未找到