1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
|
#include "mongoose.h"
#include "json.hpp"
using json = nlohmann::json;
#include <string>
#include <functional>
namespace ws
{
mg_mgr mgr;
mg_connection *c = nullptr;
bool done = false;
std::function<void()> onConnect;
static void cb(struct mg_connection *c, int ev, void *ev_data, void *fn_data) {
if (ev == MG_EV_WS_OPEN) {
puts("Open");
} else if (ev == MG_EV_WS_MSG) {
struct mg_ws_message *wm = (struct mg_ws_message *) ev_data;
printf("Msg: %.*s\n", (int)wm->data.len, wm->data.ptr);
std::string jsonStr(wm->data.ptr, wm->data.len);
auto msg = json::parse(jsonStr);
int op = msg["op"].get<int>();
if (op == 0) {
json response = {
{"op", 1},
{"d", {
{"rpcVersion", 1},
}}
};
auto responseStr = response.dump();
mg_ws_send(c, responseStr.c_str(), responseStr.size(), WEBSOCKET_OP_TEXT);
}
else if (op == 2)
{
puts("Connected");
if (onConnect)
onConnect();
}
}
if (ev == MG_EV_ERROR) {
printf("Error: %s\n", (char*)ev_data);
done = true;
}
if (ev == MG_EV_CLOSE) {
puts("Close");
done = true;
}
}
void init()
{
mg_mgr_init(&mgr);
}
void connect(std::string address)
{
c = mg_ws_connect(&mgr, address.c_str(), cb, nullptr, nullptr);
}
void update()
{
if (c && !done)
mg_mgr_poll(&mgr, 10);
}
void sendRequest(std::string requestType)
{
json request = { { "op", 6 },
{ "d",
{
{ "requestType", requestType },
{ "requestId", std::to_string(time(nullptr)).c_str() }
} } };
auto requestStr = request.dump();
mg_ws_send(c, requestStr.c_str(), requestStr.size(), WEBSOCKET_OP_TEXT);
}
}
|