Modbus TCP是一种基于以太网TCP/IP的Modbus协议变种,它允许Modbus协议在以太网网络上运行,使得设备之间可以通过IP网络交换数据。Modbus由MODICON公司于1979年开发,是一种工业现场总线协议标准,广泛应用于工业自动化领域。
#region ModBusTCP 地址解释
/* 00 01->事务标识符,随意指定
00 00->协议标识符,Modbus TCP协议标识符为0x0000
00 06->报文长度,表示后面的报文长度为6个字节
01->广播地址
03->功能码 0x01 读输出线圈
0x02 读离散输入
0x03 读保持寄存器
0x04 读输入寄存器
0x05 写单个线圈
0x06 写单个保持寄存器
0x0F 写多个线圈
0x10 写多个保持寄存器
00 64 读写地址高八位 低八位
00 01 寄存器数量
*/
using System;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Threading.Tasks;
namespace ModbusTcpExample
{
class Program
{
static void Main(string[] args)
{
MBTCP mBTCP = new MBTCP();
mBTCP.MDConnection("192.168.1.2", 502);
}
}
class MBTCP
{
private bool ConnectionStatus = false;
NetworkStream stream;
//ModBusTCP启动
public void MDConnection(string ipAddress, int port)
{
try
{
TcpClient client = new TcpClient(ipAddress, port);
stream = client.GetStream();
ConnectionStatus = true;
}
catch (Exception e)
{