using System;
using System.Net.Sockets;
namespace ModbusTCPExample
{
class Program
{
static void Main(string[] args)
{
// 创建一个 TCP 客户端
using (TcpClient client = new TcpClient("127.0.0.1", 502))
{
// 获取网络流
NetworkStream stream = client.GetStream();
// 构建 Modbus 请求报文
// 这里假设我们要读取保持寄存器 (功能码 03),起始地址为 0,读取 1 个寄存器
byte[] request = new byte[]
{
0x00, 0x00, // 事务标识符
0x00, 0x00, // 协议标识符
0x00, 0x06, // 长度
0x01, // 单元标识符
0x03, // 功能码 (03 - 读保持寄存器)
0x00, 0x00, // 起始地址
0x00, 0x01 // 寄存器数量
};
// 发送请求
stream.Write(request, 0, request.Length);
// 接收响应
byte[] response = new byte[256];
int bytesRead = stream.Read(response, 0, response.Length);
// 解析响应
if (bytesRead >= 9 && response[7] == 0x03) // 检查功能码是否匹配
{
// 响应数据从第 9 字节开始
byte byteCount = response[8];
for (int i = 0; i < byteCount; i++)
{
Console.WriteLine($"Byte {i}: {response[9 + i]:X2}");
}
}
else
{
Console.WriteLine("Invalid response or function code mismatch.");
}
}
}
}
}
TcpClient
类连接到 Modbus TCP 服务器(这里假设服务器在本地,端口为 502)。NetworkStream
将请求发送到服务器。NetworkStream
中读取服务器的响应,并检查响应的有效性。这段代码展示了如何使用 C# 实现一个简单的 Modbus TCP 客户端,用于与 Modbus TCP 服务器进行通信。
上一篇:c# math.round
下一篇:c# listbox
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站