Skip to main content

Constructor

OpcUaSession Provides multiple overloads: a minimal "endpoint-only" constructor, a username constructor, an encryption constructor, and a fully configured constructor. There are also two static encryption shortcut factories.

Prerequisite Reading
public OpcUaSession(String endpointUrl)
public OpcUaSession(String endpointUrl, String username, String password)
public OpcUaSession(String endpointUrl,
Enums.MessageSecurityMode mode,
String username, String password)
public OpcUaSession(String endpointUrl,
Enums.MessageSecurityMode mode,
String username, String password,
int sessionTimeoutMs, int requestTimeoutMs, int connectTimeoutMs)

The first two parameters are specified explicitly ( Enums.MessageSecurityMode.None in plain text). The last two unlisted parameters take their default values: keepAliveIntervalMs = 10000,autoReconnect = true, autoPublishOnConnect = true, and all four certificate parameters (clientCertPath / clientKeyPath / serverCertPath / securityPolicyUri) are set to null.

Examples​

import com.darra.opcua.*;

// 1. Anonymous + Plaintext (Development Phase)
try (OpcUaSession ua = new OpcUaSession("opc.tcp://localhost:4840")) {
ua.connect();
}

// 2. Username + Plaintext
try (OpcUaSession ua = new OpcUaSession(
"opc.tcp://server:4840", "operator", "secret")) {
ua.connect();
}
public static OpcUaSession secureSign(String endpointUrl, String clientCertPath)
public static OpcUaSession secureSignAndEncrypt(String endpointUrl, String clientCertPath)

The default parameters are pre-configured (Basic256Sha256, auto-reconnect, 10-second heartbeat); simply use the endpoint followed by a colon (:) PFX:

import com.darra.opcua.*;

// Sign (Tamper-proof, but not sniffer-proof)
try (OpcUaSession ua = OpcUaSession.secureSign(
"opc.tcp://server:4840", "C:\\certs\\client.pfx")) {
ua.connect();
}

// SignAndEncrypt (Typical Production)
try (OpcUaSession ua = OpcUaSession.secureSignAndEncrypt(
"opc.tcp://server:4840", "C:\\certs\\client.pfx")) {
ua.connect();
}

Full Configuration Structure​

public OpcUaSession(String endpointUrl,
Enums.MessageSecurityMode securityMode,
String username, String password,
int sessionTimeoutMs, int requestTimeoutMs, int connectTimeoutMs,
int keepAliveIntervalMs, boolean autoReconnect, boolean autoPublishOnConnect,
String clientCertPath, String clientKeyPath, String serverCertPath,
String securityPolicyUri)

Parameters​

CategoryPropertyTypeAccessDescription
RequiredendpointUrlStringinOPC UA Endpoint, in the format opc.tcp://host:port
SecuritysecurityModeEnums.MessageSecurityModeinNone / Sign / SignAndEncrypt
securityPolicyUriStringinnull = Automatically selected based on mode (None → #None, others → #Basic256Sha256)
clientCertPathStringinClient PFX path (Sign / SignAndEncrypt required), containing the private key
clientKeyPathStringinPrivate key path — the current private key comes with the PFX; this parameter is kept to align with the Stack. Just pass null; it is not the PFX password
serverCertPathStringinOptional: server certificate DER path; if not provided, the None→Secure automatic upgrade is used
LoginusernameStringinnull = Anonymous, non-null = UsernameIdentityToken
passwordStringinUsed with username
TimeoutsessionTimeoutMsintinServer-side session timeout / keep-alive duration (default 60000 = 60 seconds; do not set it too short)
requestTimeoutMsintinSingle RPC timeout (default 5000 = 5 seconds, including large Read / Write / Browse requests)
connectTimeoutMsintinConnection establishment timeout (default 10000 = 10 seconds, including a 4-step handshake)
RuntimekeepAliveIntervalMsintinKeepAlive heartbeat interval (typically 10000; 0 = disabled)
autoReconnectbooleaninAutomatically reconnect after a disconnection
autoPublishOnConnectbooleaninAutomatically start the background publish thread when connect() is called

Example — Anonymous + Sign Encryption​

import com.darra.opcua.*;

try (OpcUaSession ua = new OpcUaSession(
"opc.tcp://server:4840",
Enums.MessageSecurityMode.Sign,
null, null, // Anonymous
60_000, 5_000, 10_000, // Session / RPC / Connect Timeout
10_000, true, true, // KeepAlive / autoReconnect / autoPublish
"C:\\certs\\client.pfx", null, // clientCertPath = PFX (contains a private key); clientKeyPath = path to the private key; currently provided by the class PFX itself; pass null
null, null)) { // serverCertPath Do not pass → None → Secure: Automatic upgrade; leave blank securityPolicyUri to automatically select based on mode
ua.connect();
}

Example — Constructing a Result GetEndpoints Factory​

import com.darra.opcua.*;
import java.util.List;

List<EndpointDescription> endpoints =
OpcUaDiscovery.getEndpoints("opc.tcp://server:4840");

EndpointDescription ep = endpoints.stream()
.filter(e -> e.getSecurityMode() == Enums.MessageSecurityMode.SignAndEncrypt)
.findFirst()
.orElseThrow();

try (OpcUaSession ua = new OpcUaSession(
ep.getEndpointUrl(),
ep.getSecurityMode(),
"operator", "secret",
60_000, 5_000, 10_000,
10_000, true, true,
"C:\\certs\\client.pfx", null, // clientCertPath = PFX; clientKeyPath Pass null
null, // serverCertPath Do Not Pass → None → Secure Automatic Upgrade
ep.getSecurityPolicyUri())) { // Reuse the policy published by the server URI
ua.connect();
}

Exception​

ExceptionReason
IllegalArgumentExceptionendpointUrl null or an empty string
OpcUaException ("Session_Create failed")Base layer DarraUa_Session_Create returns non-0; ex.statusCode = Enums.StatusCode.fromCode(rc), ex.rawCode = raw int code

During construction, only the Session_Create path throws an OpcUaException. ensureStackInitialized() does not check the return value of DarraUa_Initialize(), so no exception is thrown during the constructor phase due to "Stack initialization failed"; certificate loading failures occur in the connect() phase, not during construction.

Resource Management​

OpcUaSession Implementation AutoCloseable: Internal maintenance of process-level reference counting + native stack initialization. You must use try-with-resources or explicitly call close.:

import com.darra.opcua.*;

// Recommended: "try-with-resources" for automatic closing
try (OpcUaSession ua = new OpcUaSession("opc.tcp://server:4840")) {
ua.connect();
// ...
}

// or explicitly
OpcUaSession ua = new OpcUaSession("opc.tcp://server:4840");
try {
ua.connect();
// ...
} finally {
ua.close();
}

close() Calling close destroys DarraUa_Session_Close the session and decrements the process-level stack reference count (shutting down the stack when it reaches zero); this is generally try-with-resources sufficient. After calling close, the instance can no longer connect; a new one must be created OpcUaSession.

Stack reference counting

SDK: A process-level shared native Stack. The Stack is initialized when the first OpcUaSession is created, and shut down when the last one is closed. If a session is not closed, the Stack will remain in the process indefinitely; this does not affect functionality but causes memory usage to increase.

Next Step​