【问题标题】:C# - Image - Binary Formatter Deserialization Error - Does not contain a valid BinaryHeaderC# - 图像 - 二进制格式化程序反序列化错误 - 不包含有效的 BinaryHeader
【发布时间】:2016-05-02 00:55:23
【问题描述】:

我制作了一个通过 TCP 套接字发送图像的程序,它可以运行一段时间然后总是在服务器端反序列化流时出错。

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

导致错误的完整功能是:

private void handleClientThread(TcpClient tcpClient)
{
    while (true)
    {
        BinaryFormatter binaryFormatter = new BinaryFormatter();
        pictureBox1.Image = (Image)binaryFormatter.Deserialize(tcpClient.GetStream()); // this line is the one throwing an exception
        pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
    }

}

客户端正在正确发送所有内容:

private Image TakePicture()
{
    Bitmap bmpScreenCapture = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
    Graphics g = Graphics.FromImage(bmpScreenCapture);
    g.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, bmpScreenCapture.Size, CopyPixelOperation.SourceCopy);

    return bmpScreenCapture;
}

private void SendPicture()
{
    Image clientPicture = TakePicture();

    BinaryFormatter binaryFormatter = new BinaryFormatter();
    binaryFormatter.Serialize(sharerClient.GetStream(), clientPicture);
}

谁能帮我解决这个问题或帮我通过 TCP 套接字发送图像而不引发异常。

【问题讨论】:

  • 完全删除BinaryFormatter,只发送像素数据(或者更好的是,压缩像素数据,如PNG)。 BinaryFormatter 很慢,不能互操作,而且是版本控制的噩梦——它早就应该被弃用了。
  • 你能给我举个例子来说明我将如何发送它,我花了大约 2 个小时试图让它工作而不使用 BinaryFormatter 无济于事
  • 我现在没有太多时间来写答案,但本质上是:调用Bitmap.Save,将网络流传递给它。不过,您可能必须首先发送带有图像大小(以字节为单位)的标头,因此您可以为此使用中介 MemoryStream。另一方面,使用带有Stream 参数的构造函数重载构造一个Bitmap
  • 无法确定整个图像是否会被一体接收(事实上,很可能不会)。您可以只获得一个字节,然后必须稍等片刻才能获得更多(NetworkStream 不这样做)。实现消息框架,例如length- and header-prefixing,然后当你知道你收到整个图像时,你可以反序列化它。
  • 用 C# 做视觉思维?

标签: c# sockets tcp


【解决方案1】:
private void SendPicture()
{
    Image clientPicture = TakePicture();
    clientPicture.Save(sharerClient.GetStream(), ImageFormat.Png);
}

我想出了 Lucas Trzesniewski,但我将如何在服务器端做到这一点?

【讨论】:

  • 如果您的意思是如何接收图像,您可以使用Image.FromStream()。但请记住,您仍然会遇到仅获取图像一部分的问题。你真的必须实现某种消息框架,否则它的工作机会很小,
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-21
  • 2013-09-23
  • 2015-09-17
相关资源
最近更新 更多