跳到主要内容

连接 / 断开

前置阅读

Connect()

void Connect();

建立到 endpoint 的连接. 内部串行执行:

  1. Hello — 协商 BufferSize / MaxMessageSize
  2. OpenSecureChannel — 协商加密通道 (None / Sign / SignAndEncrypt)
  3. GetEndpoints — 拉取服务端 Endpoint 列表 (用于校验)
  4. CreateSession — 创建会话, 协商 SessionTimeout
  5. ActivateSession — 用 UserToken 激活
  6. 加载 NamespaceArray 到 s.NamespacesRef()
  7. (可选) 启动 AutoPublish 后台线程
  8. (可选) 启动 KeepAlive 心跳

成功后:

  • s.IsConnected() == true
  • s.State() == SessionState::Connected
  • s.Events().on_connected 回调触发

失败抛 Exception 携带具体 StatusCode (Status::BadCommunicationError / BadConnectionRejected / BadSecurityModeRejected / ...).

例子

#include <darra/opcua/client.hpp>
#include <iostream>

using namespace darra::opcua;

int main() {
Stack::Init();
Session s("opc.tcp://localhost:4840");

s.Events().on_connected = [](std::string const& url) {
std::cout << "Connected to " << url << "\n";
};
s.Events().on_state_changed = [](SessionState old_s, SessionState new_s, Status reason) {
std::cout << static_cast<int>(old_s) << " -> "
<< static_cast<int>(new_s)
<< " (reason=0x" << std::hex << static_cast<uint32_t>(reason) << ")\n";
};

try {
s.Connect();
} catch (Exception const& ex) {
std::cerr << "Connect failed: " << ex.what() << "\n";
Stack::Shutdown();
return 1;
}

Stack::Shutdown();
return 0;
}

Disconnect()

void Disconnect();

主动断开连接, 但保留 Session 实例可重连. 内部:

  1. 停 KeepAlive 心跳线程
  2. 停 AutoPublish 后台线程
  3. 关 Session (CloseSession + CloseSecureChannel)
  4. 触发 s.Events().on_disconnected 回调

Session 析构时也会自动调用 Disconnect() + Free handle, 不必手动, 直接靠 RAII 即可:

{
Session s("opc.tcp://localhost:4840");
s.Connect();
// ...
} // ← 离开作用域自动 Disconnect

重连同一实例

s.Disconnect();
// ... 等待 / 业务处理 ...
s.Connect(); // 同一实例可以多次 Connect

自动重连 (内置)

SDK 检测到底层通讯异常时自动:

Connected
↓ (异常)
Reconnecting (on_reconnecting 触发)
↓ (重试 N 次)
├── 成功 → Reconnected (on_reconnected 触发) → 自动 Republish 订阅
└── 失败 → Disconnected (on_disconnected 触发)

重连参数通过 ConnectionConfig:

ConnectionConfig cfg;
cfg.endpoint_url = "opc.tcp://server:4840";
cfg.auto_reconnect = true; // 默认 true
cfg.reconnect_max_retries = 5; // 默认 3
cfg.reconnect_delay_ms = 1500; // 默认 2000
Session s(cfg);
s.Connect();

状态查询

SessionState st = s.State();
// Disconnected / Connecting / Connected / Reconnecting / Closing / Failed

bool ok = s.IsConnected(); // == (State() == Connected)

SessionState 枚举:

含义
Disconnected (0)未连接 / 已断开
Connecting (1)正在 Connect (Hello / OpenSecureChannel)
Connected (2)已连接, 可正常 Read / Write / Subscribe
Reconnecting (3)检测到断线, 自动重连中
Closing (4)正在 Disconnect / 析构
Failed (5)重连失败终态, 需要新建实例

下一步