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();