websocket_client_test.cpp 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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.onmessage = [&ws](const std::string& msg) {
  23. printf("onmessage(type=%s len=%d): %.*s\n", ws.opcode() == WS_OPCODE_TEXT ? "text" : "binary",
  24. (int)msg.size(), (int)msg.size(), msg.data());
  25. };
  26. ws.onclose = []() {
  27. printf("onclose\n");
  28. };
  29. // reconnect: 1,2,4,8,10,10,10...
  30. reconn_setting_t reconn;
  31. reconn_setting_init(&reconn);
  32. reconn.min_delay = 1000;
  33. reconn.max_delay = 10000;
  34. reconn.delay_policy = 2;
  35. ws.setReconnect(&reconn);
  36. http_headers headers;
  37. headers["Origin"] = "http://example.com/";
  38. ws.open(url, headers);
  39. std::string str;
  40. while (std::getline(std::cin, str)) {
  41. if (str == "close") {
  42. ws.close();
  43. } else if (str == "open") {
  44. ws.open(url, headers);
  45. } else if (str == "stop") {
  46. ws.stop();
  47. break;
  48. } else {
  49. if (!ws.isConnected()) break;
  50. ws.send(str);
  51. }
  52. }
  53. return 0;
  54. }