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();
}
}
TcpClient 用于创建客户端连接,而 NetworkStream 用于读写数据。PlcCommunication 类并进行基本的发送和接收操作。这段代码展示了如何通过 TCP/IP 协议与 PLC 进行简单的通讯。实际应用中,可能需要根据具体的 PLC 型号和协议进行调整。
上一篇:c#界面开发
下一篇:c# split()函数
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站