websocket_server_test.cpp 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /*
  2. * websocket server
  3. *
  4. * @build make examples
  5. * @server bin/websocket_server_test 8888
  6. * @client bin/websocket_client_test ws://127.0.0.1:8888/
  7. * @js html/websocket_client.html
  8. *
  9. */
  10. #include "WebSocketServer.h"
  11. #include "EventLoop.h"
  12. #include "htime.h"
  13. #include "hssl.h"
  14. using namespace hv;
  15. int main(int argc, char** argv) {
  16. if (argc < 2) {
  17. printf("Usage: %s port\n", argv[0]);
  18. return -10;
  19. }
  20. int port = atoi(argv[1]);
  21. WebSocketServerCallbacks ws;
  22. ws.onopen = [](const WebSocketChannelPtr& channel, const std::string& url) {
  23. printf("onopen: GET %s\n", url.c_str());
  24. // send(time) every 1s
  25. setInterval(1000, [channel](TimerID id) {
  26. if (channel->isConnected()) {
  27. char str[DATETIME_FMT_BUFLEN] = {0};
  28. datetime_t dt = datetime_now();
  29. datetime_fmt(&dt, str);
  30. channel->send(str);
  31. } else {
  32. killTimer(id);
  33. }
  34. });
  35. };
  36. ws.onmessage = [](const WebSocketChannelPtr& channel, const std::string& msg) {
  37. printf("onmessage: %s\n", msg.c_str());
  38. };
  39. ws.onclose = [](const WebSocketChannelPtr& channel) {
  40. printf("onclose\n");
  41. };
  42. websocket_server_t server;
  43. server.port = port;
  44. #if 0
  45. server.ssl = 1;
  46. hssl_ctx_init_param_t param;
  47. memset(&param, 0, sizeof(param));
  48. param.crt_file = "cert/server.crt";
  49. param.key_file = "cert/server.key";
  50. if (hssl_ctx_init(&param) == NULL) {
  51. fprintf(stderr, "SSL certificate verify failed!\n");
  52. return -20;
  53. }
  54. #endif
  55. server.ws = &ws;
  56. websocket_server_run(&server);
  57. return 0;
  58. }