websocket.hpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /**
  2. * Copyright (c) 2020 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. #ifndef RTC_WEBSOCKET_H
  19. #define RTC_WEBSOCKET_H
  20. #if ENABLE_WEBSOCKET
  21. #include "channel.hpp"
  22. #include "include.hpp"
  23. #include "init.hpp"
  24. #include "message.hpp"
  25. #include "queue.hpp"
  26. #include <atomic>
  27. #include <optional>
  28. #include <thread>
  29. #include <variant>
  30. namespace rtc {
  31. class TcpTransport;
  32. class TlsTransport;
  33. class WsTransport;
  34. class WebSocket final : public Channel, public std::enable_shared_from_this<WebSocket> {
  35. public:
  36. WebSocket();
  37. WebSocket(const string &url);
  38. ~WebSocket();
  39. void open(const string &url);
  40. void close() override;
  41. bool send(const std::variant<binary, string> &data) override;
  42. bool isOpen() const override;
  43. bool isClosed() const override;
  44. size_t maxMessageSize() const override;
  45. // Extended API
  46. std::optional<std::variant<binary, string>> receive() override;
  47. size_t availableAmount() const override; // total size available to receive
  48. private:
  49. void remoteClose();
  50. bool outgoing(mutable_message_ptr message);
  51. std::shared_ptr<TcpTransport> initTcpTransport();
  52. std::shared_ptr<TlsTransport> initTlsTransport();
  53. std::shared_ptr<WsTransport> initWsTransport();
  54. void closeTransports();
  55. init_token mInitToken = Init::Token();
  56. std::shared_ptr<TcpTransport> mTcpTransport;
  57. std::shared_ptr<TlsTransport> mTlsTransport;
  58. std::shared_ptr<WsTransport> mWsTransport;
  59. std::recursive_mutex mInitMutex;
  60. string mScheme, mHost, mHostname, mService, mPath;
  61. std::atomic<bool> mIsOpen = false;
  62. std::atomic<bool> mIsClosed = false;
  63. Queue<message_ptr> mRecvQueue;
  64. std::atomic<size_t> mRecvAmount = 0;
  65. };
  66. } // namespace rtc
  67. #endif
  68. #endif // NET_WEBSOCKET_H