1
0

websocket_server_test.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. WebSocketServerCallbacks ws;
  34. ws.onopen = [](const WebSocketChannelPtr& channel, const std::string& url) {
  35. printf("onopen: GET %s\n", url.c_str());
  36. // send(time) every 1s
  37. setInterval(1000, [channel](TimerID id) {
  38. if (channel->isConnected()) {
  39. char str[DATETIME_FMT_BUFLEN] = {0};
  40. datetime_t dt = datetime_now();
  41. datetime_fmt(&dt, str);
  42. channel->send(str);
  43. } else {
  44. killTimer(id);
  45. }
  46. });
  47. };
  48. ws.onmessage = [](const WebSocketChannelPtr& channel, const std::string& msg) {
  49. printf("onmessage: %s\n", msg.c_str());
  50. };
  51. ws.onclose = [](const WebSocketChannelPtr& channel) {
  52. printf("onclose\n");
  53. };
  54. websocket_server_t server;
  55. server.port = port;
  56. #if TEST_WSS
  57. server.https_port = port + 1;
  58. hssl_ctx_init_param_t param;
  59. memset(&param, 0, sizeof(param));
  60. param.crt_file = "cert/server.crt";
  61. param.key_file = "cert/server.key";
  62. if (hssl_ctx_init(&param) == NULL) {
  63. fprintf(stderr, "SSL certificate verify failed!\n");
  64. return -20;
  65. }
  66. #endif
  67. server.ws = &ws;
  68. websocket_server_run(&server);
  69. return 0;
  70. }