websocket.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. ctx = mg_start(&callback_funcs, &ws_ctx, server_options);
  27. mg_set_websocket_handler(ctx, "/MyWebSock",
  28. NULL,
  29. websocket_ready_handler,
  30. websocket_data_handler,
  31. connection_close_handler,
  32. NULL);
  33. printf("Connect to localhost:%s/websock.htm\n", mg_get_option(ctx, "listening_ports"));
  34. puts("Enter an (ASCII) character or * to exit:");
  35. for (;;) {
  36. fgets(inbuf, sizeof(inbuf), stdin);
  37. if (inbuf[0]=='*') {
  38. break;
  39. }
  40. inbuf[0] = toupper(inbuf[0]);
  41. websock_send_broadcast(ctx, inbuf, 1);
  42. }
  43. mg_stop(ctx);
  44. return 0;
  45. }