WPF封裝常用通訊工具類
下面我將為您封裝常用的TCP、串口、Modbus、MQTT、WebAPI和PLC通訊工具類,適用于WPF應用程序開發。
一、TCP通訊工具類
using System;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;public class TcpClientHelper : IDisposable
{private TcpClient _tcpClient;private NetworkStream _networkStream;private readonly object _lock = new object();public event Action<string> ReceivedData;public bool IsConnected => _tcpClient?.Connected ?? false;public async Task ConnectAsync(string ipAddress, int port){try{if (_tcpClient != null && _tcpClient.Connected)await DisconnectAsync();_tcpClient = new TcpClient();