websocket.cpp 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /**
  2. * Copyright (c) 2019 Paul-Louis Ageneau
  3. *
  4. * This Source Code Form is subject to the terms of the Mozilla Public
  5. * License, v. 2.0. If a copy of the MPL was not distributed with this
  6. * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  7. */
  8. #include "rtc/rtc.hpp"
  9. #if RTC_ENABLE_WEBSOCKET
  10. #include <atomic>
  11. #include <chrono>
  12. #include <iostream>
  13. #include <memory>
  14. #include <thread>
  15. using namespace rtc;
  16. using namespace std;
  17. template <class T> weak_ptr<T> make_weak_ptr(shared_ptr<T> ptr) { return ptr; }
  18. void test_websocket() {
  19. InitLogger(LogLevel::Debug);
  20. const string myMessage = "Hello world from libdatachannel";
  21. WebSocket::Configuration config;
  22. config.disableTlsVerification = true;
  23. WebSocket ws(std::move(config));
  24. ws.onOpen([&ws, &myMessage]() {
  25. cout << "WebSocket: Open" << endl;
  26. ws.send(myMessage);
  27. });
  28. ws.onClosed([]() { cout << "WebSocket: Closed" << endl; });
  29. std::atomic<bool> received = false;
  30. ws.onMessage([&received, &myMessage](variant<binary, string> message) {
  31. if (holds_alternative<string>(message)) {
  32. string str = std::move(get<string>(message));
  33. if ((received = (str == myMessage)))
  34. cout << "WebSocket: Received expected message" << endl;
  35. else
  36. cout << "WebSocket: Received UNEXPECTED message" << endl;
  37. }
  38. });
  39. ws.open("wss://echo.websocket.org:443/");
  40. int attempts = 20;
  41. while ((!ws.isOpen() || !received) && attempts--)
  42. this_thread::sleep_for(1s);
  43. if (!ws.isOpen())
  44. throw runtime_error("WebSocket is not open");
  45. if (!received)
  46. throw runtime_error("Expected message not received");
  47. ws.close();
  48. this_thread::sleep_for(1s);
  49. cout << "Success" << endl;
  50. }
  51. #endif