websocket.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. #include "test.hpp"
  10. #if RTC_ENABLE_WEBSOCKET
  11. #include <atomic>
  12. #include <chrono>
  13. #include <iostream>
  14. #include <memory>
  15. #include <thread>
  16. using namespace rtc;
  17. using namespace std;
  18. template <class T> weak_ptr<T> make_weak_ptr(shared_ptr<T> ptr) { return ptr; }
  19. TestResult test_websocket() {
  20. InitLogger(LogLevel::Debug);
  21. const string myMessage = "Hello world from libdatachannel";
  22. WebSocket::Configuration config;
  23. config.disableTlsVerification = true;
  24. WebSocket ws(std::move(config));
  25. ws.onOpen([&ws, &myMessage]() {
  26. cout << "WebSocket: Open" << endl;
  27. ws.send(myMessage);
  28. });
  29. ws.onError([](string error) { cout << "WebSocket: Error: " << error << endl; });
  30. ws.onClosed([]() { cout << "WebSocket: Closed" << endl; });
  31. std::atomic<bool> received = false;
  32. ws.onMessage([&received, &myMessage](variant<binary, string> message) {
  33. if (holds_alternative<string>(message)) {
  34. string str = std::move(get<string>(message));
  35. if ((received = (str == myMessage)))
  36. cout << "WebSocket: Received expected message" << endl;
  37. else
  38. cout << "WebSocket: Received UNEXPECTED message" << endl;
  39. }
  40. });
  41. ws.open("wss://echo.websocket.org:443/");
  42. int attempts = 20;
  43. while ((!ws.isOpen() || !received) && attempts--)
  44. this_thread::sleep_for(1s);
  45. if (!ws.isOpen())
  46. return TestResult(false, "WebSocket is not open");
  47. if (!received)
  48. return TestResult(false, "Expected message not received");
  49. ws.close();
  50. this_thread::sleep_for(1s);
  51. return TestResult(true);
  52. }
  53. #endif