mongoose/examples/websocket-server/main.c

49 lines
1.8 KiB
C
Raw Normal View History

2020-12-12 01:35:58 +08:00
// Copyright (c) 2020 Cesanta Software Limited
// All rights reserved
//
2021-11-23 00:45:14 +08:00
// Example Websocket server. See https://mongoose.ws/tutorials/websocket-server/
2020-12-12 01:35:58 +08:00
#include "mongoose.h"
2021-11-03 00:53:57 +08:00
static const char *s_listen_on = "ws://localhost:8000";
static const char *s_web_root = ".";
2020-12-12 01:35:58 +08:00
// This RESTful server implements the following endpoints:
// /websocket - upgrade to Websocket, and implement websocket echo server
// /api/rest - respond with JSON string {"result": 123}
2021-11-03 00:53:57 +08:00
// any other URI serves static files from s_web_root
2020-12-12 01:35:58 +08:00
static void fn(struct mg_connection *c, int ev, void *ev_data, void *fn_data) {
2021-11-03 00:53:57 +08:00
if (ev == MG_EV_OPEN) {
// c->is_hexdumping = 1;
} else if (ev == MG_EV_HTTP_MSG) {
2020-12-12 01:35:58 +08:00
struct mg_http_message *hm = (struct mg_http_message *) ev_data;
if (mg_http_match_uri(hm, "/websocket")) {
// Upgrade to websocket. From now on, a connection is a full-duplex
// Websocket connection, which will receive MG_EV_WS_MSG events.
mg_ws_upgrade(c, hm, NULL);
2020-12-12 01:35:58 +08:00
} else if (mg_http_match_uri(hm, "/rest")) {
// Serve REST response
2020-12-18 06:45:22 +08:00
mg_http_reply(c, 200, "", "{\"result\": %d}\n", 123);
2020-12-12 01:35:58 +08:00
} else {
// Serve static files
2021-11-03 00:53:57 +08:00
struct mg_http_serve_opts opts = {.root_dir = s_web_root};
mg_http_serve_dir(c, ev_data, &opts);
2020-12-12 01:35:58 +08:00
}
} else if (ev == MG_EV_WS_MSG) {
// Got websocket frame. Received data is wm->data. Echo it back!
struct mg_ws_message *wm = (struct mg_ws_message *) ev_data;
mg_ws_send(c, wm->data.ptr, wm->data.len, WEBSOCKET_OP_TEXT);
}
(void) fn_data;
}
int main(void) {
2021-11-03 00:53:57 +08:00
struct mg_mgr mgr; // Event manager
mg_mgr_init(&mgr); // Initialise event manager
printf("Starting WS listener on %s/websocket\n", s_listen_on);
2020-12-12 01:35:58 +08:00
mg_http_listen(&mgr, s_listen_on, fn, NULL); // Create HTTP listener
for (;;) mg_mgr_poll(&mgr, 1000); // Infinite event loop
mg_mgr_free(&mgr);
return 0;
}