WinForm上位机常用的通信方式有以下几种:

发布时间 2023-11-22 12:15:52作者: 泽哥的学习笔记

WinForm上位机常用的通信方式有以下几种:

  1. 串口通信:使用SerialPort类实现。

示例代码:

using System;
using System.IO.Ports;

public class SerialPortExample
{
    private SerialPort _serialPort;

    public SerialPortExample(string portName, int baudRate)
    {
        _serialPort = new SerialPort(portName, baudRate);
        _serialPort.Open();
    }

    public void SendData(string data)
    {
        _serialPort.Write(data);
    }

    public string ReceiveData()
    {
        return _serialPort.ReadExisting();
    }

    public void Close()
    {
        _serialPort.Close();
    }
}
  1. TCP通信:使用Socket类实现。

示例代码:

using System;
using System.Net;
using System.Net.Sockets;

public class TcpClientExample
{
    private TcpClient _tcpClient;

    public TcpClientExample(string ipAddress, int port)
    {
        _tcpClient = new TcpClient(ipAddress, port);
    }

    public void SendData(string data)
    {
        byte[] buffer = Encoding.UTF8.GetBytes(data);
        _tcpClient.Send(buffer);
    }

    public string ReceiveData()
    {
        byte[] buffer = new byte[1024];
        int received = _tcpClient.Receive(buffer);
        return Encoding.UTF8.GetString(buffer, 0, received);
    }

    public void Close()
    {
        _tcpClient.Close();
    }
}
  1. UDP通信:使用UdpClient类实现。

示例代码:

using System;
using System.Net;
using System.Net.Sockets;

public class UdpClientExample
{
    private UdpClient _udpClient;

    public UdpClientExample(string ipAddress, int port)
    {
        _udpClient = new UdpClient(ipAddress, port);
    }

    public void SendData(string data)
    {
        byte[] buffer = Encoding.UTF8.GetBytes(data);
        _udpClient.Send(buffer, buffer.Length);
    }

    public string ReceiveData()
    {
        byte[] buffer = new byte[1024];
        int received = _udpClient.Receive(buffer);
        return Encoding.UTF8.GetString(buffer, 0, received);
    }

    public void Close()
    {
        _udpClient.Close();
    }
}