1
0

websocket_client_test.cpp 1013 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. };
  22. ws.onclose = []() {
  23. printf("onclose\n");
  24. };
  25. ws.onmessage = [](const std::string& msg) {
  26. printf("onmessage: %s\n", msg.c_str());
  27. };
  28. // reconnect: 1,2,4,8,10,10,10...
  29. ReconnectInfo reconn;
  30. reconn.min_delay = 1000;
  31. reconn.max_delay = 10000;
  32. reconn.delay_policy = 2;
  33. ws.setReconnect(&reconn);
  34. ws.open(url);
  35. std::string str;
  36. while (std::getline(std::cin, str)) {
  37. if (ws.isConnected()) {
  38. ws.send(str);
  39. }
  40. }
  41. return 0;
  42. }