"using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Data;\nusing System.Drawing;\nusing System.Linq;\nusing System.Text;\nusing System.Windows.Forms;\nusing System.Net.Sockets;\nusing System.Threading;\nusing System.Net;\nusing System.IO;\n\nnamespace sop_client\n{\n public partial class main : Form\n {\n private TcpClient client;\n private NetworkStream stream;\n private Thread receiveThread;\n private bool continueReceiving;\n private TcpListener listener;\n\n\n public main()\n {\n InitializeComponent();\n }\n\n // 按钮点击事件,获取本机IP并发送到服务器\n private void button1_Click(object sender, EventArgs e)\n {\n if (client == null || !client.Connected)\n {\n ConnectToServer();\n button1.Text = "停止连接";\n }\n else\n {\n Disconnect();\n button1.Text = "开始连接";\n }\n string localIP = GetLocalIPAddress();\n textBox1.Text = localIP;\n //SendIPAddress(localIP);\n }\n\n // 获取本机IP地址\n private string GetLocalIPAddress()\n {\n string localIP = "";\n var host = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());\n foreach (var ip in host.AddressList)\n {\n if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)\n {\n localIP = ip.ToString();\n break;\n }\n }\n return localIP;\n }\n // 连接到服务器\n private void ConnectToServer()\n {\n try\n {\n if (client != null && client.Connected)\n {\n return;\n }\n\n string serverIP = textBox3.Text;\n int serverPort = 1024;\n\n client = new TcpClient();\n client.Connect(serverIP, serverPort);\n\n stream = client.GetStream();\n\n // 提取本机 IP 地址\n string localIP = GetLocalIPAddress();\n\n // 发送本机 IP 地址到服务器\n byte[] ipBytes = Encoding.ASCII.GetBytes(localIP);\n stream.Write(ipBytes, 0, ipBytes.Length);\n\n // 接收连接成功字符串\n byte[] responseBytes = new byte[client.ReceiveBufferSize];\n int bytesRead = stream.Read(responseBytes, 0, responseBytes.Length);\n string response = Encoding.ASCII.GetString(responseBytes, 0, bytesRead);\n string response1 = "Connected successfully";\n // 在TextBox2中显示连接成功字符串\n if (response == response1)\n {\n label3.Text = response1;\n label3.ForeColor = Color.DarkGreen;\n }\n else\n {\n label3.Text = response;\n label3.ForeColor = Color.Red;\n }\n\n // 启动一个线程来接收图片\n receiveThread = new Thread(ReceiveImages);\n receiveThread.Start();\n }\n catch (Exception ex)\n {\n MessageBox.Show(ex.ToString());\n }\n }\n // 断开连接\n private void Disconnect()\n {\n try\n {\n if (client == null)\n {\n return;\n }\n\n continueReceiving = false;\n stream.Close();\n client.Close();\n client = null; // 释放套接字资源\n //listener.Stop();\n listener = null;\n }\n catch (Exception ex)\n {\n MessageBox.Show(ex.ToString());\n }\n }\n\n // 接收图片\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 listener.Stop();\n }\n\n // 显示图片\n private void ShowImage(string imagePath)\n {\n // 在 UI 线程中显示图片\n pictureBox1.Invoke((MethodInvoker)delegate\n {\n pictureBox1.Image = Image.FromFile(imagePath);\n });\n }\n\n // 窗口关闭时关闭连接和线程\n private void main_FormClosed(object sender, FormClosedEventArgs e)\n {\n try\n {\n if (client != null && client.Connected)\n {\n client.Close();\n\n }\n if (listener != null)\n {\n listener.Stop();\n }\n if (receiveThread != null && receiveThread.IsAlive)\n {\n receiveThread.Abort();\n }\n\n\n }\n catch (Exception ex)\n {\n MessageBox.Show(ex.ToString());\n }\n }\n }\n}\n

C# TCP 客户端代码优化:防止重复连接错误

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

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