我已经创建了一个通过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套接字发送图像而不会抛出异常。
答案 0 :(得分:0)
private void SendPicture()
{
Image clientPicture = TakePicture();
clientPicture.Save(sharerClient.GetStream(), ImageFormat.Png);
}
我想出了Lucas Trzesniewski,但我如何在服务器端做到这一点?