【发布时间】: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# 做视觉思维?