我正在创建一个包含视频聊天部分的应用程序,因此我必须发送和接收图像。当我尝试从流中获取接收到的图像时,会发生此异常。堆栈溢出中没有任何答案对我有帮助,所以我指望您。
我试图通过try catch结构来处理此问题,只是捕获并释放异常,但是在输出中会发生异常,并且在一段时间后视频发送停止工作。
private void Listener()
{
byte[] buffer = new byte[100000];
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
socket.Bind(receiveEndPoint);
socket.Listen(5);
using (Socket client = socket.Accept())
{
while (client.Receive(buffer) > 0)
{
Thread.Sleep(10);
var size = client.Receive(buffer);
MemoryStream stream = new MemoryStream(buffer, 0, size);
if (pictureBox2.InvokeRequired) { pictureBox2.Invoke(new MethodInvoker(() => ImageSetter(stream))); } else ImageSetter(stream);
stream.Position = 0;
}
}
}
}
private void ImageSetter(MemoryStream stream)
{
try
{
pictureBox2.Image = Image.FromStream(stream);
}
catch (Exception) { }
}
我也尝试过这样做。在这种情况下,异常没有得到处理。
private void Listener()
{
byte[] buffer = new byte[100000];
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
socket.Bind(receiveEndPoint);
socket.Listen(5);
using (Socket client = socket.Accept())
{
while (client.Receive(buffer) > 0)
{
Thread.Sleep(10);
var size = client.Receive(buffer);
MemoryStream stream = new MemoryStream(buffer, 0, size);
pictureBox2.Image = Image.FromStream(stream);
stream.Position = 0;
}
}
}
}
正如我所说,它实际上可以工作一段时间,但是随后视频发送过程停止工作,所以我想要一个没有尝试捕获的解决方案。