1 #include "App.h"
2
3 struct us_listen_socket_t *global_listen_socket;
4
main()5 int main() {
6
7 /* ws->getUserData returns one of these */
8 struct PerSocketData {
9 /* Fill with user data */
10 std::vector<std::string> topics;
11 int nr = 0;
12 };
13
14 /* Keep in mind that uWS::SSLApp({options}) is the same as uWS::App() when compiled without SSL support.
15 * You may swap to using uWS:App() if you don't need SSL */
16 uWS::SSLApp *app = new uWS::SSLApp({
17 /* There are example certificates in uWebSockets.js repo */
18 .key_file_name = "../misc/key.pem",
19 .cert_file_name = "../misc/cert.pem",
20 .passphrase = "1234"
21 });
22
23 app->ws<PerSocketData>("/*", {
24 /* Settings */
25 .compression = uWS::DISABLED,
26 .maxPayloadLength = 16 * 1024 * 1024,
27 .idleTimeout = 60,
28 .maxBackpressure = 16 * 1024 * 1024,
29 .closeOnBackpressureLimit = false,
30 .resetIdleTimeoutOnSend = true,
31 .sendPingsAutomatically = false,
32 /* Handlers */
33 .upgrade = nullptr,
34 .open = [](auto *ws) {
35 /* Open event here, you may access ws->getUserData() which points to a PerSocketData struct */
36
37 PerSocketData *perSocketData = (PerSocketData *) ws->getUserData();
38
39 for (int i = 0; i < 32; i++) {
40 std::string topic = std::to_string((uintptr_t)ws) + "-" + std::to_string(i);
41 perSocketData->topics.push_back(topic);
42 ws->subscribe(topic);
43 }
44 },
45 .message = [&app](auto *ws, std::string_view message, uWS::OpCode opCode) {
46 PerSocketData *perSocketData = (PerSocketData *) ws->getUserData();
47
48 app->publish(perSocketData->topics[(size_t)(++perSocketData->nr % 32)], message, opCode);
49 ws->publish(perSocketData->topics[(size_t)(++perSocketData->nr % 32)], message, opCode);
50 },
51 .drain = [](auto */*ws*/) {
52 /* Check ws->getBufferedAmount() here */
53 //std::cout << "drain" << std::endl;
54 },
55 .ping = [](auto */*ws*/, std::string_view ) {
56 /* Not implemented yet */
57 },
58 .pong = [](auto */*ws*/, std::string_view ) {
59 /* Not implemented yet */
60 },
61 .close = [](auto */*ws*/, int /*code*/, std::string_view /*message*/) {
62 /* You may access ws->getUserData() here */
63 }
64 }).listen(9001, [](auto *listen_s) {
65 if (listen_s) {
66 std::cout << "Listening on port " << 9001 << std::endl;
67 //listen_socket = listen_s;
68 }
69 });
70
71 app->run();
72
73 delete app;
74
75 uWS::Loop::get()->free();
76 }
77