Skip to main content

Connect / Disconnect

Prerequisite Reading
  • Please review the construction parameters first Constructor.
  • For encryption settings, see Security.
  • For information on event subscriptions after connecting, see Events.

connect()​

public void connect();

Establish a connection to the endpoint. Internal serial execution:

  1. Hello — Negotiate BufferSize / MaxMessageSize
  2. OpenSecureChannel — Negotiated Encryption Channel (None / Sign / SignAndEncrypt)
  3. GetEndpoints — Retrieve the list of server endpoints (for validation)
  4. CreateSession — Establish a session, negotiate SessionTimeout
  5. ActivateSession — Activate UserToken with
  6. Loading NamespaceArray to namespaces
  7. Automatically Start a autoPublishOnConnect = true Background Thread
  8. Automatically Enable KeepAlive

After successful completion:

  • isConnected() == true
  • getState() == Enums.SessionState.Connected
  • events.onConnected ListenerTrigger (ConnectionEventArgs)

Failure throw OpcUaException with the specific StatusCode (BadCertificateInvalid / BadIdentityTokenRejected / BadCommunicationError / ...).

Examples​

import com.darra.opcua.*;

try (OpcUaSession ua = new OpcUaSession("opc.tcp://localhost:4840")) {
ua.events.onConnected.add(e ->
System.out.println("Connected to " + e.endpointUrl));
ua.events.onStateChanged.add(e ->
System.out.println(e.oldState + " → " + e.newState + " (reason=" + e.reason + ")"));

try {
ua.connect();
} catch (OpcUaException ex) {
System.err.println("Connect failed: " + ex.statusCode + " (" + ex.getMessage() + ")");
}
}

disconnect()​

public void disconnect();

Disconnect the connection proactively, but keep the instance OpcUaSession open for reconnection. Internally:

  1. Stop KeepAlive
  2. Adjust the base layer DarraUa_Session_Disconnect Close Session + SecureChannel
  3. If it was previously in Connected, issue events.onStateChanged and events.onDisconnected (ConnectionEventArgs.message = "主动断开")

close() Takes a different approach: DarraUa_Session_Close Destroy the session and decrement the process-level stack reference count (shut down the stack when it reaches zero), Do not call disconnect(); After closing the instance, it cannot be reconnected to; a new instance must be created OpcUaSession. Generally, this is sufficient try-with-resources; there is no need to explicitly disconnect.

Reconnect to the same instance​

import com.darra.opcua.*;

try (OpcUaSession ua = new OpcUaSession("opc.tcp://server:4840")) {
ua.connect();
// ... Business ...
ua.disconnect();
// ... Waiting / Processing ...
ua.connect(); // A single instance can be connected to multiple times
// ...
}

Automatic Reconnection (Built-in)​

autoReconnect=true Enable when constructed. When an underlying communication error is detected SDK, automatically:

Connected
↓ (communication error)
Reconnecting (events.onReconnecting fires)
↓ (retries N times)
├── Success → Reconnected (events.onReconnected fires) → auto Republish of subscriptions
└── Failure → Disconnected (events.onDisconnected fires)

Reconnection Parameter Description:

ParametersDefaultAvailableNote
Number of retries3NoFixed by the underlying stack; not exposed on the Java side
Retry Interval2000 msNoFixed by the underlying stack; not exposed on the Java side
Reconnection timeout10000 msYesConstruction Parameters connectTimeoutMs

Java SDK No environment variable toggle (OPCUA_RECONNECT_MAX Variables such OPCUA_RECONNECT_INTERVAL_MS as "/" do not exist in any of the six SDK languages; do not include them in the deployment script.) The number of retries and the interval between retries are fixed and cannot be configured.

Status Inquiry​

Enums.SessionState s = ua.getState();
// Disconnected / Connecting / Connected / Reconnecting / Closing / Failed

boolean ok = ua.isConnected(); // == (getState() == Enums.SessionState.Connected)

Enums.SessionState Enumeration:

ValueMeaning
DisconnectedNot connected / Disconnected
ConnectingConnecting (Hello / OpenSecureChannel)
ConnectedConnected; read, write, and subscribe operations are working normally.
ReconnectingA disconnection has been detected; automatically reconnecting
ClosingDisconnecting / Closing...
FailedReconnection failed (final state); the instance is still available and can be retried connect() (see "Reconnecting to the Same Instance" above)

Next Step​