websocket.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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 <chrono>
  21. #include <iostream>
  22. #include <memory>
  23. #include <thread>
  24. #include <atomic>
  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. ws->onOpen([wws = make_weak_ptr(ws), &myMessage]() {
  33. auto ws = wws.lock();
  34. if (!ws)
  35. return;
  36. cout << "WebSocket: Open" << endl;
  37. ws->send(myMessage);
  38. });
  39. ws->onClosed([]() { cout << "WebSocket: Closed" << endl; });
  40. std::atomic<bool> received = false;
  41. ws->onMessage([&received, &myMessage](const variant<binary, string> &message) {
  42. if (holds_alternative<string>(message)) {
  43. string str = get<string>(message);
  44. if((received = (str == myMessage)))
  45. cout << "WebSocket: Received expected message" << endl;
  46. else
  47. cout << "WebSocket: Received UNEXPECTED message" << endl;
  48. }
  49. });
  50. ws->open("wss://echo.websocket.org/");
  51. int attempts = 10;
  52. while ((!ws->isOpen() || !received) && attempts--)
  53. this_thread::sleep_for(1s);
  54. if (!ws->isOpen())
  55. throw runtime_error("WebSocket is not open");
  56. if(!received)
  57. throw runtime_error("Expected message not received");
  58. ws->close();
  59. this_thread::sleep_for(1s);
  60. // You may call rtc::Cleanup() when finished to free static resources
  61. rtc::Cleanup();
  62. this_thread::sleep_for(1s);
  63. cout << "Success" << endl;
  64. }
  65. #endif