Client-Side Redundancy and Server Failover
Client-side reconnection routing: When there are multiple server addresses, if the current one is unreachable, switch to the next one and re-establish the subscription. This is client-side routing; it is not server high availability, nor does it constitute a commitment to active-standby redundancy. Use C# Example.
Sample Configuration
- Mass Monitoring → Mass Surveillance
- Bridge to Modbus → OPC UA → Modbus TCP Bridging
Complete Code
using DarraOpcUa_Client;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
class FailoverClient : IDisposable
{
private readonly string[] _endpoints;
private readonly IReadOnlyList<string> _tags;
private DarraOpcUa _ua;
private OpcUaSubscription _sub;
private int _currentIdx = -1;
private readonly object _lock = new();
public FailoverClient(IReadOnlyList<string> tags, params string[] endpoints)
{
_tags = tags;
_endpoints = endpoints;
}
public void Connect()
{
lock (_lock)
{
// Start retrying from the next endpoint (to avoid repeatedly connecting to the same faulty endpoint)
for (int tries = 0; tries < _endpoints.Length; tries++)
{
_currentIdx = (_currentIdx + 1) % _endpoints.Length;
var ep = _endpoints[_currentIdx];
try
{
_ua = new DarraOpcUa(ep);
_ua.Events.CommunicationError += OnCommError;
_ua.Connect();
Console.WriteLine($"[OK] 已连接 {ep}");
Resubscribe();
return;
}
catch (OpcUaException ex)
{
Console.WriteLine($" {ep} 连接失败: {ex.StatusCode}");
_ua?.Dispose();
_ua = null;
}
}
throw new Exception("所有 endpoint 都不可达");
}
}
private void Resubscribe()
{
_sub = _ua.CreateSubscription(500);
_sub.DataChanged += (s, e) =>
Console.WriteLine($" {e.NodeId} = {e.ValueString} [{e.Status}]");
_sub.AddMany(_tags);
}
private void OnCommError(object sender, CommunicationErrorEventArgs e)
{
Console.WriteLine($"\n[!!] 通讯异常 {e.StatusCode}, 切换 server...");
Task.Run(() =>
{
try { _sub?.Dispose(); } catch (Exception ex) { Console.WriteLine($"释放订阅失败: {ex.Message}"); }
try { _ua?.Dispose(); } catch (Exception ex) { Console.WriteLine($"释放会话失败: {ex.Message}"); }
Thread.Sleep(2000); // Wait until fault detection stabilizes to avoid repeated switching and jitter.
try { Connect(); }
catch (Exception ex) { Console.WriteLine($"切换失败: {ex.Message}, 30 秒后重试"); }
});
}
public void Dispose() { _sub?.Dispose(); _ua?.Dispose(); }
}
class Program
{
static async Task Main()
{
var tags = new[] { "ns=2;s=Boiler1.Temperature", "ns=2;s=Boiler1.Pressure" };
using var client = new FailoverClient(
tags,
"opc.tcp://primary:4840",
"opc.tcp://backup:4840");
client.Connect();
Console.WriteLine("\n运行中. 断开当前 endpoint 的网络测试切换. Ctrl+C 退出.\n");
await Task.Delay(Timeout.Infinite);
}
}
Code Highlights
CommunicationErrorTriggered when a communication error occurs; the client does not need to send a probe on its own. Once triggered, reconnect by switching to a different endpoint as shown in this example.- Before the switch, backoff
Thread.Sleep(2000)was used to filter out network fluctuations; without it, there would be constant fluctuations. In a production environment, it is recommended to switch to exponential backoff. _currentIdx = (_currentIdx + 1) % _endpoints.LengthStart with the next endpoint to avoid repeatedly connecting to the same faulty point.- After changing the endpoint, all old sessions and subscriptions become invalid and must
CreateSubscriptionbe recreatedAddMany; the target endpointTransferSubscriptionsmust be able to recognize the original subscription, which most deployments do not support. - The for each endpoint NamespaceArray must be consistent; otherwise,
ns=2;...switching to it might map to a completely different node.
Important Notes
- Each endpoint mustThe Same NamespaceArray (NodeId Consistent), otherwise, after the switch, it may
ns=2;...map to a completely different node. - To detect communication anomalies more quickly, set
Modify(...)to a lower valuemaxKeepAliveCount, but setting it too low may result in false positives. - During long-term operation, you also need to handle a chain of failures where "the next endpoint goes down as well"; the code above handles this using a looped index combined with exception retries.