websocket_client_test.cpp 931 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. /*
  2. * websocket client
  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 "WebSocketClient.h"
  11. using namespace hv;
  12. int main(int argc, char** argv) {
  13. if (argc < 2) {
  14. printf("Usage: %s url\n", argv[0]);
  15. return -10;
  16. }
  17. const char* url = argv[1];
  18. WebSocketClient ws;
  19. ws.onopen = [&ws]() {
  20. printf("onopen\n");
  21. ws.send("hello");
  22. };
  23. ws.onclose = []() {
  24. printf("onclose\n");
  25. };
  26. ws.onmessage = [](const std::string& msg) {
  27. printf("onmessage: %s\n", msg.c_str());
  28. };
  29. // reconnect: 1,2,4,8,10,10,10...
  30. ReconnectInfo reconn;
  31. reconn.min_delay = 1000;
  32. reconn.max_delay = 10000;
  33. reconn.delay_policy = 2;
  34. ws.setReconnect(&reconn);
  35. ws.open(url);
  36. while (1) hv_delay(1000);
  37. return 0;
  38. }