websocket.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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
  11. main(void)
  12. {
  13. struct mg_context *ctx = 0;
  14. struct mg_callbacks callback_funcs = {0};
  15. tWebSockContext ws_ctx;
  16. char inbuf[4];
  17. const char *server_options[] = {
  18. /* document_root: The path to the test function websock.htm */
  19. "document_root",
  20. "../../examples/websocket",
  21. /* port: use http standard to match websocket url in websock.htm:
  22. ws://127.0.0.1/MyWebSock */
  23. /* if the port is changed here, it needs to be changed in
  24. websock.htm as well */
  25. "listening_ports",
  26. "80",
  27. NULL};
  28. callback_funcs.init_context = websock_init_lib;
  29. callback_funcs.exit_context = websock_exit_lib;
  30. ctx = mg_start(&callback_funcs, &ws_ctx, server_options);
  31. mg_set_websocket_handler(ctx,
  32. "/MyWebSock",
  33. NULL,
  34. websocket_ready_handler,
  35. websocket_data_handler,
  36. connection_close_handler,
  37. NULL);
  38. printf("Connect to localhost:%s/websock.htm\n",
  39. mg_get_option(ctx, "listening_ports"));
  40. puts("Enter an (ASCII) character or * to exit:");
  41. for (;;) {
  42. fgets(inbuf, sizeof(inbuf), stdin);
  43. if (inbuf[0] == '*') {
  44. break;
  45. }
  46. inbuf[0] = toupper(inbuf[0]);
  47. websock_send_broadcast(ctx, inbuf, 1);
  48. }
  49. mg_stop(ctx);
  50. return 0;
  51. }