websocket.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /**
  2. * Copyright (c) 2020-2021 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. #if RTC_ENABLE_WEBSOCKET
  19. #include "websocket.hpp"
  20. #include "include.hpp"
  21. #include "impl/websocket.hpp"
  22. #include <regex>
  23. #ifdef _WIN32
  24. #include <winsock2.h>
  25. #endif
  26. namespace rtc {
  27. using namespace std::placeholders;
  28. WebSocket::WebSocket() : WebSocket(Configuration()) {}
  29. WebSocket::WebSocket(Configuration config)
  30. : CheshireCat<impl::WebSocket>(std::move(config)),
  31. Channel(std::dynamic_pointer_cast<impl::Channel>(CheshireCat<impl::WebSocket>::impl())) {}
  32. WebSocket::~WebSocket() { impl()->remoteClose(); }
  33. WebSocket::State WebSocket::readyState() const { return impl()->state; }
  34. bool WebSocket::isOpen() const { return impl()->state.load() == State::Open; }
  35. bool WebSocket::isClosed() const { return impl()->state.load() == State::Closed; }
  36. size_t WebSocket::maxMessageSize() const { return DEFAULT_MAX_MESSAGE_SIZE; }
  37. void WebSocket::open(const string &url) {
  38. PLOG_VERBOSE << "Opening WebSocket to URL: " << url;
  39. impl()->parse(url);
  40. impl()->changeState(State::Connecting);
  41. impl()->initTcpTransport();
  42. }
  43. void WebSocket::close() {
  44. auto state = impl()->state.load();
  45. if (state == State::Connecting || state == State::Open) {
  46. PLOG_VERBOSE << "Closing WebSocket";
  47. impl()->changeState(State::Closing);
  48. if (auto transport = impl()->getWsTransport())
  49. transport->close();
  50. else
  51. impl()->changeState(State::Closed);
  52. }
  53. }
  54. bool WebSocket::send(message_variant data) {
  55. return impl()->outgoing(make_message(std::move(data)));
  56. }
  57. bool WebSocket::send(const byte *data, size_t size) {
  58. return impl()->outgoing(make_message(data, data + size));
  59. }
  60. } // namespace rtc
  61. #endif