channel.hpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. #ifndef RTC_CHANNEL_H
  19. #define RTC_CHANNEL_H
  20. #include "include.hpp"
  21. #include <atomic>
  22. #include <functional>
  23. #include <variant>
  24. namespace rtc {
  25. class Channel {
  26. public:
  27. virtual void close() = 0;
  28. virtual bool send(const std::variant<binary, string> &data) = 0;
  29. virtual std::optional<std::variant<binary, string>> receive() = 0;
  30. virtual bool isOpen() const = 0;
  31. virtual bool isClosed() const = 0;
  32. virtual size_t availableAmount() const { return 0; }
  33. size_t bufferedAmount() const;
  34. void onOpen(std::function<void()> callback);
  35. void onClosed(std::function<void()> callback);
  36. void onError(std::function<void(const string &error)> callback);
  37. void onMessage(std::function<void(const std::variant<binary, string> &data)> callback);
  38. void onMessage(std::function<void(const binary &data)> binaryCallback,
  39. std::function<void(const string &data)> stringCallback);
  40. void onAvailable(std::function<void()> callback);
  41. void onBufferedAmountLow(std::function<void()> callback);
  42. void setBufferedAmountLowThreshold(size_t amount);
  43. protected:
  44. virtual void triggerOpen();
  45. virtual void triggerClosed();
  46. virtual void triggerError(const string &error);
  47. virtual void triggerAvailable(size_t count);
  48. virtual void triggerBufferedAmount(size_t amount);
  49. private:
  50. synchronized_callback<> mOpenCallback;
  51. synchronized_callback<> mClosedCallback;
  52. synchronized_callback<const string &> mErrorCallback;
  53. synchronized_callback<const std::variant<binary, string> &> mMessageCallback;
  54. synchronized_callback<> mAvailableCallback;
  55. synchronized_callback<> mBufferedAmountLowCallback;
  56. std::atomic<size_t> mBufferedAmount = 0;
  57. std::atomic<size_t> mBufferedAmountLowThreshold = 0;
  58. };
  59. } // namespace rtc
  60. #endif // RTC_CHANNEL_H