1
0

websocket_server_test.cpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. class MyContext {
  28. public:
  29. MyContext() {
  30. timerID = INVALID_TIMER_ID;
  31. }
  32. ~MyContext() {
  33. }
  34. int handleMessage(const std::string& msg) {
  35. printf("onmessage: %s\n", msg.c_str());
  36. return msg.size();
  37. }
  38. TimerID timerID;
  39. };
  40. int main(int argc, char** argv) {
  41. if (argc < 2) {
  42. printf("Usage: %s port\n", argv[0]);
  43. return -10;
  44. }
  45. int port = atoi(argv[1]);
  46. WebSocketServerCallbacks ws;
  47. ws.onopen = [](const WebSocketChannelPtr& channel, const std::string& url) {
  48. printf("onopen: GET %s\n", url.c_str());
  49. MyContext* ctx = channel->newContext<MyContext>();
  50. // send(time) every 1s
  51. ctx->timerID = setInterval(1000, [channel](TimerID id) {
  52. char str[DATETIME_FMT_BUFLEN] = {0};
  53. datetime_t dt = datetime_now();
  54. datetime_fmt(&dt, str);
  55. channel->send(str);
  56. });
  57. };
  58. ws.onmessage = [](const WebSocketChannelPtr& channel, const std::string& msg) {
  59. MyContext* ctx = channel->getContext<MyContext>();
  60. ctx->handleMessage(msg);
  61. };
  62. ws.onclose = [](const WebSocketChannelPtr& channel) {
  63. printf("onclose\n");
  64. MyContext* ctx = channel->getContext<MyContext>();
  65. if (ctx->timerID != INVALID_TIMER_ID) {
  66. killTimer(ctx->timerID);
  67. }
  68. channel->deleteContext<MyContext>();
  69. };
  70. websocket_server_t server;
  71. server.port = port;
  72. #if TEST_WSS
  73. server.https_port = port + 1;
  74. hssl_ctx_init_param_t param;
  75. memset(&param, 0, sizeof(param));
  76. param.crt_file = "cert/server.crt";
  77. param.key_file = "cert/server.key";
  78. if (hssl_ctx_init(&param) == NULL) {
  79. fprintf(stderr, "SSL certificate verify failed!\n");
  80. return -20;
  81. }
  82. #endif
  83. server.ws = &ws;
  84. websocket_server_run(&server);
  85. return 0;
  86. }