Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c#与plc通讯

作者:寂寞味道   发布日期:2026-04-18   浏览:70

using System;
using System.Net.Sockets;

// 示例代码:C# 与 PLC 通讯(使用简单的 TCP/IP 连接)
public class PlcCommunication
{
    private TcpClient tcpClient;
    private NetworkStream networkStream;

    public PlcCommunication(string ipAddress, int port)
    {
        tcpClient = new TcpClient(ipAddress, port);
        networkStream = tcpClient.GetStream();
    }

    // 发送数据到PLC
    public void SendData(byte[] data)
    {
        if (networkStream != null && networkStream.CanWrite)
        {
            networkStream.Write(data, 0, data.Length);
            Console.WriteLine("发送数据成功");
        }
    }

    // 从PLC接收数据
    public byte[] ReceiveData(int bufferSize)
    {
        byte[] buffer = new byte[bufferSize];
        if (networkStream != null && networkStream.CanRead)
        {
            int bytesRead = networkStream.Read(buffer, 0, bufferSize);
            Console.WriteLine($"接收到 {bytesRead} 字节的数据");
            return buffer;
        }
        return null;
    }

    // 关闭连接
    public void CloseConnection()
    {
        if (networkStream != null)
        {
            networkStream.Close();
        }
        if (tcpClient != null)
        {
            tcpClient.Close();
        }
    }
}

// 使用示例
class Program
{
    static void Main(string[] args)
    {
        string ipAddress = "192.168.1.10"; // PLC的IP地址
        int port = 502; // PLC的端口号

        PlcCommunication plcComm = new PlcCommunication(ipAddress, port);

        // 发送数据到PLC
        byte[] sendData = new byte[] { 0x01, 0x02, 0x03, 0x04 };
        plcComm.SendData(sendData);

        // 接收来自PLC的数据
        byte[] receiveData = plcComm.ReceiveData(1024);
        if (receiveData != null)
        {
            Console.WriteLine("接收到的数据: " + BitConverter.ToString(receiveData));
        }

        // 关闭连接
        plcComm.CloseConnection();
    }
}

解释说明:

  1. TcpClient 和 NetworkStream:用于建立与 PLC 的 TCP/IP 连接。TcpClient 用于创建客户端连接,而 NetworkStream 用于读写数据。
  2. SendData 方法:将指定的字节数组发送到 PLC。
  3. ReceiveData 方法:从 PLC 接收指定大小的数据,并返回一个字节数组。
  4. CloseConnection 方法:关闭与 PLC 的连接。
  5. Main 方法:演示如何实例化 PlcCommunication 类并进行基本的发送和接收操作。

这段代码展示了如何通过 TCP/IP 协议与 PLC 进行简单的通讯。实际应用中,可能需要根据具体的 PLC 型号和协议进行调整。

上一篇:c#界面开发

下一篇:c# split()函数

大家都在看

c# 二进制

c# 创建目录

c# socket服务端连接多个客户端

c# datatable group by

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

c# invoke方法

.net和c#

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站