websocket.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // Copyright (c) 2004-2012 Sergey Lyubka
  2. // This file is a part of mongoose project, http://github.com/valenok/mongoose
  3. #include <stdio.h>
  4. #include <string.h>
  5. #include "mongoose.h"
  6. static void *callback(enum mg_event event, struct mg_connection *conn) {
  7. if (event == MG_WEBSOCKET_READY) {
  8. static const char *hello = "hello from mongoose! waiting for message ...";
  9. char frame[2];
  10. // Prepare websocket frame.
  11. frame[0] = 0x81; // text frame
  12. frame[1] = strlen(hello); // length is < 126
  13. // Write frame and a text message
  14. mg_write(conn, frame, sizeof(frame));
  15. mg_write(conn, hello, strlen(hello));
  16. return "";
  17. } else if (event == MG_WEBSOCKET_MESSAGE) {
  18. unsigned char buf[500], reply[500];
  19. int len, msg_len, i, mask_len, xor;
  20. // Read message from the client and echo it back
  21. if ((len = mg_read(conn, buf, sizeof(buf))) > 8) {
  22. msg_len = buf[1] & 127;
  23. mask_len = (buf[1] & 128) ? 4 : 0;
  24. if (msg_len < 126) {
  25. reply[0] = 0x81; // text, FIN set
  26. reply[1] = msg_len;
  27. for (i = 0; i < msg_len; i++) {
  28. xor = mask_len == 0 ? 0 : buf[2 + (i % 4)];
  29. reply[i + 2] = buf[i + 2 + mask_len] ^ xor;
  30. }
  31. mg_write(conn, reply, 2 + msg_len);
  32. }
  33. }
  34. return ""; // Return non-NULL: stop websocket conversation
  35. } else {
  36. return NULL;
  37. }
  38. }
  39. int main(void) {
  40. struct mg_context *ctx;
  41. const char *options[] = {
  42. "listening_ports", "8080",
  43. "document_root", "websocket_html_root",
  44. NULL
  45. };
  46. ctx = mg_start(&callback, NULL, options);
  47. getchar(); // Wait until user hits "enter"
  48. mg_stop(ctx);
  49. return 0;
  50. }