websocket.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. auto ws = std::make_shared<WebSocket>();
  32. // Certificate verification can be disabled
  33. // auto ws = std::make_shared<WebSocket>(WebSocket::Configuration{.disableTlsVerification =
  34. // true});
  35. ws->onOpen([wws = make_weak_ptr(ws), &myMessage]() {
  36. auto ws = wws.lock();
  37. if (!ws)
  38. return;
  39. cout << "WebSocket: Open" << endl;
  40. ws->send(myMessage);
  41. });
  42. ws->onClosed([]() { cout << "WebSocket: Closed" << endl; });
  43. std::atomic<bool> received = false;
  44. ws->onMessage([&received, &myMessage](variant<binary, string> message) {
  45. if (holds_alternative<string>(message)) {
  46. string str = std::move(get<string>(message));
  47. if ((received = (str == myMessage)))
  48. cout << "WebSocket: Received expected message" << endl;
  49. else
  50. cout << "WebSocket: Received UNEXPECTED message" << endl;
  51. }
  52. });
  53. ws->open("wss://echo.websocket.org:443/");
  54. int attempts = 10;
  55. while ((!ws->isOpen() || !received) && attempts--)
  56. this_thread::sleep_for(1s);
  57. if (!ws->isOpen())
  58. throw runtime_error("WebSocket is not open");
  59. if (!received)
  60. throw runtime_error("Expected message not received");
  61. ws->close();
  62. this_thread::sleep_for(1s);
  63. cout << "Success" << endl;
  64. }
  65. #endif