C# TCP 接收图片:解决套接字地址重复使用错误
{ 'title': '// 接收图片\n private void ReceiveImages()\n {\n continueReceiving = true;\n TcpListener listener = new TcpListener(IPAddress.Parse(GetLocalIPAddress()), 1025);\n\n listener.Start();\n\n while (continueReceiving)\n {\n try\n {\n\n\n\n TcpClient imageClient = listener.AcceptTcpClient();\n NetworkStream imageStream = imageClient.GetStream();\n\n // 先接收图像数据的长度\n byte[] lengthBytes = new byte[4];\n imageStream.Read(lengthBytes, 0, 4);\n int length = BitConverter.ToInt32(lengthBytes, 0);\n\n byte[] imageData = new byte[length];\n int totalBytesRead = 0;\n int bytesRead = 0;\n\n while (totalBytesRead < length &&\n (bytesRead = imageStream.Read(imageData, totalBytesRead, length - totalBytesRead)) > 0)\n {\n totalBytesRead += bytesRead;\n }\n\n if (totalBytesRead > 0)\n {\n using (MemoryStream ms = new MemoryStream(imageData))\n {\n Image receivedImage = Image.FromStream(ms);\n\n // 在PictureBox中展示图片\n pictureBox1.Image = receivedImage;\n }\n }\n // 关闭并释放套接字资源\n imageStream.Close();\n imageClient.Close();\n }\n catch (Exception ex)\n {\n MessageBox.Show(ex.ToString());\n }\n\n }\n // 停止监听并释放套接字资源\n //receiveThread.Abort();\n listener.Stop();\n } 这个接受图片的方法中,如果点击按钮1调用了Disconnect()方法,然后再次点击按钮1,则会提示 listener.Start();这一行套接字地址只允许使用一次”的错误内容:这个错误是因为在调用Disconnect()方法后,套接字listener被关闭并释放资源,所以再次调用ReceiveImages()方法时无法重新启动listener。要解决这个问题,可以在调用Disconnect()方法时加入一个标志位,表示是否已经断开连接。然后在ReceiveImages()方法中根据这个标志位来决定是否重新启动listener。
示例代码如下:
private bool isDisconnected = false;
// 断开连接
private void Disconnect()
{
isDisconnected = true;
// 关闭并释放套接字资源
listener.Stop();
}
// 接收图片
private void ReceiveImages()
{
isDisconnected = false;
TcpListener listener = new TcpListener(IPAddress.Parse(GetLocalIPAddress()), 1025);
listener.Start();
while (continueReceiving && !isDisconnected)
{
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());
}
}
if (!isDisconnected)
{
// 停止监听并释放套接字资源
listener.Stop();
}
}
在调用Disconnect()方法时,设置isDisconnected为true。在ReceiveImages()方法中,添加了一个判断条件,如果isDisconnected为true,则不重新启动listener并退出循环。这样即使断开连接后再次点击按钮1,就不会出现'套接字地址只允许使用一次'的错误了。
原文地址: https://www.cveoy.top/t/topic/qgcL 著作权归作者所有。请勿转载和采集!