2022-07-15 18:32:16 -03:00
|
|
|
// Copyright (c) 2020 Cesanta Software Limited
|
|
|
|
// All rights reserved
|
|
|
|
//
|
|
|
|
// Example Websocket server with timers. This is a simple Websocket echo
|
|
|
|
// server, which sends a message to all connected clients periodically,
|
|
|
|
// using timer API.
|
|
|
|
|
|
|
|
#include "mongoose.h"
|
|
|
|
|
|
|
|
static const char *s_listen_on = "http://localhost:8000";
|
|
|
|
static const char *s_web_root = "web_root";
|
|
|
|
|
2024-01-08 17:34:34 -03:00
|
|
|
static void fn(struct mg_connection *c, int ev, void *ev_data) {
|
2022-07-15 18:32:16 -03:00
|
|
|
if (ev == MG_EV_HTTP_MSG) {
|
|
|
|
struct mg_http_message *hm = (struct mg_http_message *) ev_data;
|
2024-04-17 16:13:10 -03:00
|
|
|
if (mg_match(hm->uri, mg_str("/api/watch"), NULL)) {
|
2022-07-15 18:32:16 -03:00
|
|
|
mg_ws_upgrade(c, hm, NULL); // Upgrade HTTP to Websocket
|
2023-04-14 10:11:12 -03:00
|
|
|
c->data[0] = 'W'; // Set some unique mark on the connection
|
2022-07-15 18:32:16 -03:00
|
|
|
} else {
|
|
|
|
struct mg_http_serve_opts opts = {.root_dir = s_web_root};
|
|
|
|
mg_http_serve_dir(c, ev_data, &opts);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Push to all watchers
|
|
|
|
static void push(struct mg_mgr *mgr, const char *name, const void *data) {
|
|
|
|
struct mg_connection *c;
|
|
|
|
for (c = mgr->conns; c != NULL; c = c->next) {
|
2023-01-09 10:58:07 +00:00
|
|
|
if (c->data[0] != 'W') continue;
|
2023-05-17 14:26:45 -03:00
|
|
|
mg_ws_printf(c, WEBSOCKET_OP_TEXT, "{%m:%m,%m:%m}", MG_ESC("name"),
|
|
|
|
MG_ESC(name), MG_ESC("data"), MG_ESC(data));
|
2022-07-15 18:32:16 -03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
static void timer_fn(void *arg) {
|
|
|
|
struct mg_mgr *mgr = (struct mg_mgr *) arg;
|
|
|
|
char buf[50];
|
|
|
|
mg_snprintf(buf, sizeof(buf), "[%lu, %d]", (unsigned long) time(NULL),
|
|
|
|
10 + (int) ((double) rand() * 10 / RAND_MAX));
|
|
|
|
push(mgr, "metrics", buf);
|
|
|
|
}
|
|
|
|
|
|
|
|
int main(void) {
|
2022-08-01 11:19:32 +01:00
|
|
|
struct mg_mgr mgr; // Event manager
|
|
|
|
mg_mgr_init(&mgr); // Initialise event manager
|
|
|
|
mg_log_set(MG_LL_DEBUG); // Set log level
|
2022-07-15 18:32:16 -03:00
|
|
|
mg_timer_add(&mgr, 2000, MG_TIMER_REPEAT, timer_fn, &mgr);
|
|
|
|
mg_http_listen(&mgr, s_listen_on, fn, NULL); // Create HTTP listener
|
|
|
|
for (;;) mg_mgr_poll(&mgr, 500); // Infinite event loop
|
|
|
|
mg_mgr_free(&mgr); // Free manager resources
|
|
|
|
return 0;
|
|
|
|
}
|