1 #include <iostream>
2 #include <chrono>
3 #include <thread>
4 #include "wampcc/wampcc.h"
5
6 using namespace wampcc;
7 using namespace std::chrono_literals;
8
9 int main() {
10 try {
11 // 配置 Swamp 服务器连接参数
12 wampcc::config cfg;
13 cfg.realm = "usv-realm-1";
14 cfg.uri = "ws://127.0.0.1";
15 cfg.port = 9102;
16 cfg.authid = "test_swamp";
17
18 // 创建 wampcc 会话
19 wampcc::kernel kernel;
20 auto session = wampcc::wsession::create(kernel);
21
22 // 连接到 Swamp 服务器
23 session->open(cfg);
24
25 // 订阅 /topic/2 和 /topic/3
26 session->subscribe("/topic/2", [](wampcc::wsession&, const std::string& topic, const json_value& data) {
27 std::cout << "Received message on " << topic << ": " << data.dump() << std::endl;
28 });
29
30 session->subscribe("/topic/3", [](wampcc::wsession&, const std::string& topic, const json_value& data) {
31 std::cout << "Received message on " << topic << ": " << data.dump() << std::endl;
32 });
33
34 // 发布到 /topic/1
35 json_value message = json_object();
36 message["id"] = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
37 message["ts"] = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
38 message["content"] = json_object();
39 message["content"]["arguments"] = json_object();
40
41 session->publish("/topic/1", message);
42
43 // 使程序保持运行
44 std::this_thread::sleep_for(10s);
45
46 // 关闭连接
47 session->close();
48
49 } catch (const std::exception& e) {
50 std::cerr << "Exception: " << e.what() << std::endl;
51 }
52
53 return 0;
54 }