2
0

websocket.cpp 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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.onError([](string error) { cout << "WebSocket: Error: " << error << endl; });
  29. ws.onClosed([]() { cout << "WebSocket: Closed" << endl; });
  30. std::atomic<bool> received = false;
  31. ws.onMessage([&received, &myMessage](variant<binary, string> message) {
  32. if (holds_alternative<string>(message)) {
  33. string str = std::move(get<string>(message));
  34. if ((received = (str == myMessage)))
  35. cout << "WebSocket: Received expected message" << endl;
  36. else
  37. cout << "WebSocket: Received UNEXPECTED message" << endl;
  38. }
  39. });
  40. ws.open("wss://echo.websocket.org:443/");
  41. int attempts = 20;
  42. while ((!ws.isOpen() || !received) && attempts--)
  43. this_thread::sleep_for(1s);
  44. if (!ws.isOpen())
  45. throw runtime_error("WebSocket is not open");
  46. if (!received)
  47. throw runtime_error("Expected message not received");
  48. ws.close();
  49. this_thread::sleep_for(1s);
  50. cout << "Success" << endl;
  51. }
  52. #endif