websocket_server_test.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. * websocket server
  3. *
  4. * @build make examples
  5. * @server bin/websocket_server_test 9999
  6. * @client bin/websocket_client_test ws://127.0.0.1:9999/
  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. /*
  15. * #define TEST_WSS 1
  16. *
  17. * @build ./configure --with-openssl && make clean && make
  18. *
  19. * @server bin/websocket_server_test 9999
  20. *
  21. * @client bin/websocket_client_test ws://127.0.0.1:9999/
  22. * bin/websocket_client_test wss://127.0.0.1:10000/
  23. *
  24. */
  25. #define TEST_WSS 0
  26. using namespace hv;
  27. int main(int argc, char** argv) {
  28. if (argc < 2) {
  29. printf("Usage: %s port\n", argv[0]);
  30. return -10;
  31. }
  32. int port = atoi(argv[1]);
  33. TimerID timerID = INVALID_TIMER_ID;
  34. WebSocketServerCallbacks ws;
  35. ws.onopen = [&timerID](const WebSocketChannelPtr& channel, const std::string& url) {
  36. printf("onopen: GET %s\n", url.c_str());
  37. // send(time) every 1s
  38. timerID = setInterval(1000, [channel](TimerID id) {
  39. char str[DATETIME_FMT_BUFLEN] = {0};
  40. datetime_t dt = datetime_now();
  41. datetime_fmt(&dt, str);
  42. channel->send(str);
  43. });
  44. };
  45. ws.onmessage = [](const WebSocketChannelPtr& channel, const std::string& msg) {
  46. printf("onmessage: %s\n", msg.c_str());
  47. };
  48. ws.onclose = [&timerID](const WebSocketChannelPtr& channel) {
  49. printf("onclose\n");
  50. if (timerID != INVALID_TIMER_ID) {
  51. killTimer(timerID);
  52. timerID = INVALID_TIMER_ID;
  53. }
  54. };
  55. websocket_server_t server;
  56. server.port = port;
  57. #if TEST_WSS
  58. server.https_port = port + 1;
  59. hssl_ctx_init_param_t param;
  60. memset(&param, 0, sizeof(param));
  61. param.crt_file = "cert/server.crt";
  62. param.key_file = "cert/server.key";
  63. if (hssl_ctx_init(&param) == NULL) {
  64. fprintf(stderr, "SSL certificate verify failed!\n");
  65. return -20;
  66. }
  67. #endif
  68. server.ws = &ws;
  69. websocket_server_run(&server);
  70. return 0;
  71. }