C#创建多个S7连接每个连接都是单独的线程来进行读写操作 访问PLC并使用集合或者字典存储这些连接 观察连接状态 如果断开则尝试重连 保证稳定性
以下是一个示例代码,演示了如何创建多个S7连接并使用单独的线程进行读写操作。它还使用了一个字典来存储这些连接,并观察连接状态并尝试重连以保证稳定性。
using System;
using System.Collections.Generic;
using System.Threading;
using S7.Net;
public class Program
{
private static Dictionary<string, Thread> threads = new Dictionary<string, Thread>();
private static Dictionary<string, Plc> connections = new Dictionary<string, Plc>();
public static void Main(string[] args)
{
// 添加连接
AddConnection("PLC1", "192.168.0.1", 0, 2);
AddConnection("PLC2", "192.168.0.2", 0, 2);
// 启动连接线程
foreach (var thread in threads.Values)
{
thread.Start();
}
// 保持主线程运行
while (true)
{
// 检查连接状态并尝试重连
foreach (var connection in connections.Values)
{
if (!connection.IsConnected)
{
Console.WriteLine($"{connection.Name} 断开连接,尝试重连...");
connection.Open();
}
}
// 等待一段时间再次检查连接状态
Thread.Sleep(5000);
}
}
private static void AddConnection(string name, string ipAddress, int rack, int slot)
{
var plc = new Plc(CpuType.S71200, ipAddress, rack, slot);
plc.Name = name;
connections.Add(name, plc);
var thread = new Thread(() =>
{
while (true)
{
if (plc.IsConnected)
{
// 在这里进行读写操作
// plc.Read("DB1", 0, DataType.Int16);
// plc.Write("DB1", 0, 12345);
}
// 等待一段时间再次尝试读写
Thread.Sleep(1000);
}
});
threads.Add(name, thread);
}
}
请注意,这只是一个示例代码,你需要根据你自己的需求进行修改和扩展。例如,你可以添加更多的连接,或者在读写操作中使用更多的PLC地址和数据类型
原文地址: https://www.cveoy.top/t/topic/iGBg 著作权归作者所有。请勿转载和采集!