网口同步方式一、引入依赖实现此模块所必须的库为System.Net.Sockets所用到的两个类为TcpClientNetworkStream二、作业流程1实例化类protected static TcpClient client null; protected static NetworkStream netStream null;2建立连接client new TcpClient(port, targetPort);3数据传输client.GetStream();表示从已建立的 TCP 连接中取出数据传输管道而非创建新连接或新流。client必须已成功连接否则会立即抛出InvalidOperationException返回的NetworkStream是唯一且复用的字节流通道关闭它会切断连接但获取它本身不消耗网络资源。netStream client.GetStream(); netStream.Write(data, 0, data.Length);//data是byte[]三、示例代码static void call_控制器_hstbsTCP(string port, int line, int v) { //MessageBox.Show(执行了call_控制器_hstbsTCP); var ss new string[] { , A, B, C, D }; //string targetIp 192.168.1.207; // 固定 IP int targetPort 6600; // 固定端口 if (client null) { try { client new TcpClient(port, targetPort); Debug.Write(连接状态 client null); netStream client.GetStream(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); Debug.Write(ex.ToString()); client null; netStream null; return; } } else { if (!client.Connected) { Debug.Write(连接状态 client null); client.Close(); try { client new TcpClient(port, targetPort); netStream client.GetStream(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); client null; netStream null; return; } } } var s SP ss[line] 0 v.ToString(000) #; var data System.Text.Encoding.ASCII.GetBytes(s); netStream.Write(data, 0, data.Length); }四、使用在你需要用到的这个控制方法的地方调用这个方法传入portipline通道v值即可使用。网口异步方式示例代码static void call_控制器_tcp(string ip, int port, int line, int v) { var ss new string[] { , A, B, C, D }; try { // 确保TCP连接已建立 if (tcpClient null || !tcpClient.Connected) { try { // 创建新连接带超时 tcpClient new System.Net.Sockets.TcpClient(); // 使用异步连接并设置超时 var connectTask tcpClient.ConnectAsync(ip, port); if (!connectTask.Wait(TimeSpan.FromSeconds(0.02))) // 2秒超时 { throw new TimeoutException($连接 {ip}:{port} 超时); } networkStream tcpClient.GetStream(); var remoteEndPoint (IPEndPoint)tcpClient.Client.RemoteEndPoint; currentip remoteEndPoint.Address.ToString(); } catch (Exception) { //log tcpClient?.Close(); tcpClient null; networkStream null; return; } } else { if (tcpClient.Connected currentip ! ip) { try { // 先关闭现有连接 tcpClient?.Close(); networkStream?.Close(); tcpClient null; networkStream null; // 创建新连接设置超时 tcpClient new System.Net.Sockets.TcpClient(); var connectTask tcpClient.ConnectAsync(ip, port); if (!connectTask.Wait(TimeSpan.FromSeconds(0.02))) // 2秒超时 { throw new TimeoutException($连接 {ip}:{port} 超时); } networkStream tcpClient.GetStream(); } catch (Exception ) { tcpClient?.Close(); tcpClient null; networkStream?.Close(); networkStream null; return; } } } // 示例指令格式SPX00100# 假设SP为指令头X为通道00100为亮度值 string command SP ss[line] 0 v.ToString(000) #; byte[] buffer Encoding.ASCII.GetBytes(command); networkStream.Write(buffer, 0, buffer.Length); } catch (Exception) { // 通信失败时清理资源 tcpClient?.Close(); tcpClient null; networkStream?.Close(); networkStream null; } }其他地方与上文一样