main.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // Copyright (c) 2020 Cesanta Software Limited
  2. // All rights reserved
  3. //
  4. // Example Websocket server. See https://mongoose.ws/tutorials/websocket-server/
  5. #include "mongoose.h"
  6. static const char *s_listen_on = "ws://localhost:8000";
  7. static const char *s_web_root = ".";
  8. // This RESTful server implements the following endpoints:
  9. // /websocket - upgrade to Websocket, and implement websocket echo server
  10. // /api/rest - respond with JSON string {"result": 123}
  11. // any other URI serves static files from s_web_root
  12. static void fn(struct mg_connection *c, int ev, void *ev_data, void *fn_data) {
  13. if (ev == MG_EV_OPEN) {
  14. // c->is_hexdumping = 1;
  15. } else if (ev == MG_EV_HTTP_MSG) {
  16. struct mg_http_message *hm = (struct mg_http_message *) ev_data;
  17. if (mg_http_match_uri(hm, "/websocket")) {
  18. // Upgrade to websocket. From now on, a connection is a full-duplex
  19. // Websocket connection, which will receive MG_EV_WS_MSG events.
  20. mg_ws_upgrade(c, hm, NULL);
  21. } else if (mg_http_match_uri(hm, "/rest")) {
  22. // Serve REST response
  23. mg_http_reply(c, 200, "", "{\"result\": %d}\n", 123);
  24. } else {
  25. // Serve static files
  26. struct mg_http_serve_opts opts = {.root_dir = s_web_root};
  27. mg_http_serve_dir(c, ev_data, &opts);
  28. }
  29. } else if (ev == MG_EV_WS_MSG) {
  30. // Got websocket frame. Received data is wm->data. Echo it back!
  31. struct mg_ws_message *wm = (struct mg_ws_message *) ev_data;
  32. mg_ws_send(c, wm->data.ptr, wm->data.len, WEBSOCKET_OP_TEXT);
  33. }
  34. (void) fn_data;
  35. }
  36. int main(void) {
  37. struct mg_mgr mgr; // Event manager
  38. mg_mgr_init(&mgr); // Initialise event manager
  39. printf("Starting WS listener on %s/websocket\n", s_listen_on);
  40. mg_http_listen(&mgr, s_listen_on, fn, NULL); // Create HTTP listener
  41. for (;;) mg_mgr_poll(&mgr, 1000); // Infinite event loop
  42. mg_mgr_free(&mgr);
  43. return 0;
  44. }