websocket.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /**
  2. * Copyright (c) 2019 Paul-Louis Ageneau
  3. *
  4. * This library is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU Lesser General Public
  6. * License as published by the Free Software Foundation; either
  7. * version 2.1 of the License, or (at your option) any later version.
  8. *
  9. * This library is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. * Lesser General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Lesser General Public
  15. * License along with this library; if not, write to the Free Software
  16. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  17. */
  18. #include "rtc/rtc.hpp"
  19. #if RTC_ENABLE_WEBSOCKET
  20. #include <atomic>
  21. #include <chrono>
  22. #include <iostream>
  23. #include <memory>
  24. #include <thread>
  25. using namespace rtc;
  26. using namespace std;
  27. template <class T> weak_ptr<T> make_weak_ptr(shared_ptr<T> ptr) { return ptr; }
  28. void test_websocket() {
  29. InitLogger(LogLevel::Debug);
  30. const string myMessage = "Hello world from libdatachannel";
  31. WebSocket::Configuration config;
  32. config.disableTlsVerification = true;
  33. WebSocket ws(std::move(config));
  34. ws.onOpen([&ws, &myMessage]() {
  35. cout << "WebSocket: Open" << endl;
  36. ws.send(myMessage);
  37. });
  38. ws.onClosed([]() { cout << "WebSocket: Closed" << endl; });
  39. std::atomic<bool> received = false;
  40. ws.onMessage([&received, &myMessage](variant<binary, string> message) {
  41. if (holds_alternative<string>(message)) {
  42. string str = std::move(get<string>(message));
  43. if ((received = (str == myMessage)))
  44. cout << "WebSocket: Received expected message" << endl;
  45. else
  46. cout << "WebSocket: Received UNEXPECTED message" << endl;
  47. }
  48. });
  49. ws.open("wss://echo.websocket.org:443/");
  50. int attempts = 10;
  51. while ((!ws.isOpen() || !received) && attempts--)
  52. this_thread::sleep_for(1s);
  53. if (!ws.isOpen())
  54. throw runtime_error("WebSocket is not open");
  55. if (!received)
  56. throw runtime_error("Expected message not received");
  57. ws.close();
  58. this_thread::sleep_for(1s);
  59. cout << "Success" << endl;
  60. }
  61. #endif