websocket.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /* This example uses deprecated interfaces: global websocket callbacks.
  2. They have been superseeded by URI specific callbacks.
  3. See examples/embedded_c for an up to date example.
  4. */
  5. #include <stdio.h>
  6. #include <ctype.h>
  7. #include <string.h>
  8. #include "civetweb.h"
  9. #include "WebSockCallbacks.h"
  10. int main(void)
  11. {
  12. struct mg_context *ctx = 0;
  13. struct mg_callbacks callback_funcs = {0};
  14. tWebSockContext ws_ctx;
  15. char inbuf[4];
  16. const char *server_options[] = {
  17. /* document_root: The path to the test function websock.htm */
  18. "document_root", "../../examples/websocket",
  19. /* port: use http standard to match websocket url in websock.htm: ws://127.0.0.1/MyWebSock */
  20. /* if the port is changed here, it needs to be changed in websock.htm as well */
  21. "listening_ports", "80",
  22. NULL
  23. };
  24. callback_funcs.init_context = websock_init_lib;
  25. callback_funcs.exit_context = websock_exit_lib;
  26. callback_funcs.websocket_ready = websocket_ready_handler;
  27. callback_funcs.websocket_data = websocket_data_handler;
  28. callback_funcs.connection_close = connection_close_handler;
  29. ctx = mg_start(&callback_funcs, &ws_ctx, server_options);
  30. printf("Connect to localhost:%s/websock.htm\n", mg_get_option(ctx, "listening_ports"));
  31. puts("Enter an (ASCII) character or * to exit:");
  32. for (;;) {
  33. fgets(inbuf, sizeof(inbuf), stdin);
  34. if (inbuf[0]=='*') {
  35. break;
  36. }
  37. inbuf[0] = toupper(inbuf[0]);
  38. websock_send_broadcast(ctx, inbuf, 1);
  39. }
  40. mg_stop(ctx);
  41. return 0;
  42. }