这个错误通常是由于在阻塞的AcceptTcpClient方法上调用了WSACancelBlockingCall方法导致的。要解决这个问题,你可以在调用AcceptTcpClient方法之前检查是否已经调用了WSACancelBlockingCall方法。

以下是修改后的代码:

listener.Start();

while (continueReceiving)
{
    try
    {
        if (listener.Pending()) // 检查是否有挂起的连接请求
        {
            TcpClient imageClient = listener.AcceptTcpClient();
            NetworkStream imageStream = imageClient.GetStream();

            // 先接收图像数据的长度
            byte[] lengthBytes = new byte[4];
            imageStream.Read(lengthBytes, 0, 4);
            int length = BitConverter.ToInt32(lengthBytes, 0);

            byte[] imageData = new byte[length];
            int totalBytesRead = 0;
            int bytesRead = 0;

            while (totalBytesRead < length &&
                   (bytesRead = imageStream.Read(imageData, totalBytesRead, length - totalBytesRead)) > 0)
            {
                totalBytesRead += bytesRead;
            }

            if (totalBytesRead > 0)
            {
                using (MemoryStream ms = new MemoryStream(imageData))
                {
                    Image receivedImage = Image.FromStream(ms);

                    // 在PictureBox中展示图片
                    pictureBox1.Image = receivedImage;
                }
            }

            // 关闭并释放套接字资源
            imageStream.Close();
            imageClient.Close();
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
    finally
    {
        if (!listener.Pending())
        {
            // 停止监听并释放套接字资源
            listener.Stop();
        }
    }
}

通过检查是否有挂起的连接请求,可以避免在没有连接请求时调用AcceptTcpClient方法,从而解决了报错的问题

复制代码 listenerStart; while continueReceiving try TcpClient imageClient = listenerAcceptTcpClient; NetworkStream imageStream =

原文地址: https://www.cveoy.top/t/topic/iy5A 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录