这个错误通常是因为在关闭一个套接字之后,没有正确释放该套接字的资源,然后再次使用相同的套接字地址导致的。为了解决这个问题,可以在每次接收完图片后,显式地关闭并释放相关的套接字资源。修改代码如下:

private void ReceiveImages()
{
    continueReceiving = true;
    TcpListener listener = new TcpListener(IPAddress.Parse(GetLocalIPAddress()), 1025);

    listener.Start();

    while (continueReceiving)
    {
        try
        {
            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());
        }
    }

    // 停止监听并释放套接字资源
    listener.Stop();
}

这样做可以确保每次接收完图片后都正确关闭和释放套接字资源,避免出现“每个套接字地址只允许使用一次”的错误

上述代码中 接收图片 private void ReceiveImages continueReceiving = true; TcpListener listener = new TcpListenerIPAddressParseGetLocalIPAddress 1025; listenerStar

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

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