Automatic Reconnection
Overview
Maintenance restarts or network jitter on the OPC UA Server expire client sessions. 5 core RPCs come with automatic reconnection on session-level failures plus one retry:
Read / Write / Browse / ReadHistory / Call
Process:
- Call hits the session level ( StatusCode see table below) and throws an exception
OpcUaException - Post an update Event
Category = SessionLost - Disconnect and Reconnect (Disconnect → Connect)
- Try again Business Call
- Still fails → Throw the original
OpcUaException(In the Safe version, this is collapsed to StatusCode)
Business Side Not required For these 5 RPC explicit reconnection try/catch blocks. The reconnection progress is tracked via ua.Events 's Reconnecting / Reconnected / SessionLost Share with UI.
BrowseNext that are not within the automatic reconnection scope / TranslateBrowsePaths / Subscription-class calls (CreateSubscription / Add / TransferSubscriptions) / Publish / File transfer OpcUaFile method calls Not leaving Automatic reconnection; any exceptions thrown must OpcUaException be handled by the caller.
Corresponding section of the standard: Part 4 §5.5 (SecureChannel) / §5.6 (Session).
Trigger Conditions
If any of the following status codes are encountered, it is considered a session-level failure:
| Trigger Source | Meaning |
|---|---|
StatusCode.BadSessionClosed (0x80260000) | The session has been closed by the server. |
StatusCode.BadSessionIdInvalid (0x80250000) | Session ID Failure |
StatusCode.BadServerNotConnected (0x800D0000) | Server Unreachable |
StatusCode.BadConnectionClosed (0x80AE0000) | The connection has been closed |
raw 0x80860000 (BadSecureChannelClosed) | SecureChannel Close; This code is not in the StatusCode enumeration., can only be determined 0x80860000 based on the numerical value |
OnlyThrow OpcUaException Furthermore, a reconnection is triggered only if there is a ex.StatusCode match in the table above; calls that return a value other than "Good" but do not throw an exception will not trigger a reconnection.
KeepAlive: A failed heartbeat does not trigger a reconnection — If a single heartbeat read fails, only one CommunicationError event is triggered; there is no failure count, no threshold, and no reconnection attempt.
API
| Methods / Events | Category | Reading and Writing | Note |
|---|---|---|---|
| ua.Events.SessionLost | Event | Read | Category=SessionLost, Pre-reconnection warning |
| ua.Events.Reconnecting | Event | Read | Session State Entry Reconnecting |
| ua.Events.Reconnected | Event | Read | From Reconnecting Back to Connected |
| ua.Events.Disconnected | Event | Read | Disconnected (either actively "Disconnect" or when the status changes to "Disconnected/Failed") |
Reconnecting / Reconnected It is not triggered directly by the reconnect action itself, but rather is triggered along Reconnecting with the session state transition back to Connected /.
Code Example
using System;
using System.Threading;
using DarraOpcUa_Client;
using var ua = new DarraOpcUa("opc.tcp://localhost:4840");
// 1) Attach an event to the status bar UI (WPF TextBlock)
ua.Events.Reconnecting += (s, e) =>
{
Dispatcher.Invoke(() =>
{
statusText.Text = $"重连中... {e.EndpointUrl}";
statusText.Foreground = System.Windows.Media.Brushes.Orange;
});
};
ua.Events.Reconnected += (s, e) =>
{
Dispatcher.Invoke(() =>
{
statusText.Text = "已恢复";
statusText.Foreground = System.Windows.Media.Brushes.Green;
});
};
ua.Events.SessionLost += (s, e) =>
{
Console.WriteLine($"Session 失效: {e.Message} ({e.StatusCode})");
};
ua.Connect();
// 2) You don't RPC need to write a reconnection try/catch block for these 5.
while (running)
{
var (st, dv) = ua.ReadSafe("ns=2;s=Temp");
// Even if the server restarts midway, the ReadSafe "Read" mode's automatic reconnection feature will automatically reconnect and retry once.
if (dv != null) dv.Dispose();
Thread.Sleep(1000);
}
Reconnection Policy
- Number of retries: Maximum reconnections per call 1 + 1 retry; no exponential backoff, no loops
- No wait time: Reconnect immediately
Disconnect→Connect, without a sleep in between - No Concurrency Serialization: If multiple threads simultaneously encounter a session fault, each will trigger its own reconnection; please ensure that calls to the same session are serialized on the business side, or implement your own locking mechanism.
- Reconnection timeout: Reuse the value passed during construction (
connectTimeoutMsdefault: 10 000 ms) - Reconnection Failed: Exceptions that occur during the reconnection process are not thrown; instead, the last business retry willOriginal An exception is thrown; the business logic then decides whether to display a prompt to the user based on this.
Manual Reconnection
DarraOpcUa NoneReconnect() Method. To restore manually, you must disconnect and then reconnect:
ua.Disconnect(); // Reserved Instances and Handles
// ... Waiting for the server to recover ...
ua.Connect(); // A single instance can be connected to multiple times
Relationship with Subscription Auto-Recovery
Triggered Events.Reconnected after the session reconnects; subscriptions automatically recover based on this:
- First, try
TransferSubscriptions(oldSubId)transferring the old subscription on the server to the new session. - Transfer Failed → Rebuild the entire subscription using the original subscription parameters and process each item individually
AddNode - Events Following a
Category = SubscriptionRestoredSuccessful Push
Note:
- After a rebuild, the MonitoredItem handle will change — the old mi stored on the business side becomes invalid; use
MonitoredNodeIds/RemoveByNodeIdto look up the new mi by NodeId DataChangeFilter/EventFilterDoes not participate in the rebuild; after restoration, the default behavior remains in effect; see Subscription Resumes Automatically
For more information, see Subscription Resumes Automatically。
Best Practices
- These 5 cases where you shouldn't use try/catch for reconnection RPC — Let SDK handle it; but you'll have to take care of subscriptions, browsing subsequent pages, and file transfers yourself.
- Post Events to UI — Users should see "Reconnecting..." rather than the interface freezing.
- Pre-Check Before Critical Operations
ua.State— For example, verify before setting the "Write" key parameterState == SessionState.Connected - Do not perform reconnection within a thread UI — Reconnecting may
connectTimeoutMstake a few seconds; please waitTask.Runa moment. - During testingManually disconnect the Ethernet cable for 5 seconds, Check the log to see
Reconnecting → Reconnectedif appears as expected
Cross-Language Comparison
| C# | Python | Java | C++ | Rust | C |
|---|---|---|---|---|---|
(None Reconnect(), only Disconnect() + Connect()) | (Same as above, none reconnect()) | ua.reconnect() | ua.Reconnect() | ua.reconnect() | (No manual reconnection API; only "+ DarraUa_Session_Disconnect " is allowed DarraUa_Session_Connect) |
| ua.Events.Reconnecting += ... | ua.events.reconnecting.append(cb) | events.onReconnecting(...) | events.OnReconnecting(...) | events.on_reconnecting(...) | DarraUa_Session_SetStateCallback |
| ua.Events.SessionLost += ... | ua.events.session_lost.append(cb) | events.onSessionLost(...) | events.OnSessionLost(...) | events.on_session_lost(...) | DarraUa_Session_SetStateCallback |
Side CNone DarraUa_Session_Reconnect...nor is there a function like DarraUa_RegisterReconnectingHandler DarraUa_RegisterSessionLostHandler / for event-by-event registration. Session state is uniformly handled through a single DarraUa_Session_SetStateCallback callback (state values UA_SESSION_RECONNECTING / UA_SESSION_CONNECTED / UA_SESSION_FAILED,DarraUa_Session_GetState check current state), and whether to automatically reconnect is determined DarraUa_SessionConfig by auto_reconnect 's reconnect_max_retries / reconnect_delay_ms /.
On the Python side List[Callable], the event members are, and you append(cb) subscribe to them using; on the C# side, they are event EventHandler<T>, and you subscribe += to them using.