C# 使用NModbus4进行TCP读取,并且实现自动断线重连文章来源地址https://www.toymoban.com/news/detail-708389.html
//简要版本
using Modbus.Device;
TcpClient tcp = new TcpClient();
private IModbusMaster master;
public ushort[] aa(ushort add, ushort length)
{
ushort[] a = null;
Task.Run(() =>
{
do
{
try
{
if (!tcp.Connected)
{
tcp.Connect("192.168.1.50", 502);
master = ModbusIpMaster.CreateIp(tcp);
}
a = master.ReadHoldingRegisters(1, add, length);
}
catch (Exception ex)
{
tcp.Close();
Thread.Sleep(10);
tcp = new TcpClient();
}
}
while (a == null);
}).Wait(100); // 超过100ms没执行完,就不等待了,可能是网线掉了,连接费时
return a;
}
//周期:500ms
private void timer1_Tick(object sender, EventArgs e)
{
ushort[] a = aa(1000, 4);
if (a != null)
label1.Text = a[0].ToString();
else
{
label1.Text = "xxxx";
num++;
label2.Text = num.ToString();
}
}
文章来源:https://www.toymoban.com/news/detail-708389.html
到了这里,关于C# 使用NModbus4进行TCP读取,并且实现自动断线重连的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!