websocket_client_test.cpp 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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 = []() {
  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. reconn_setting_t reconn;
  30. reconn.min_delay = 1000;
  31. reconn.max_delay = 10000;
  32. reconn.delay_policy = 2;
  33. ws.setReconnect(&reconn);
  34. http_headers headers;
  35. headers["Origin"] = "http://example.com/";
  36. ws.open(url, headers);
  37. std::string str;
  38. while (std::getline(std::cin, str)) {
  39. if (!ws.isConnected()) break;
  40. if (str == "quit") {
  41. ws.close();
  42. break;
  43. }
  44. ws.send(str);
  45. }
  46. return 0;
  47. }