channel.hpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /**
  2. * Copyright (c) 2019-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. #ifndef RTC_CHANNEL_H
  19. #define RTC_CHANNEL_H
  20. #include "common.hpp"
  21. #include "message.hpp"
  22. #include <atomic>
  23. #include <functional>
  24. #include <variant>
  25. namespace rtc {
  26. namespace impl {
  27. struct Channel;
  28. }
  29. class RTC_CPP_EXPORT Channel : private CheshireCat<impl::Channel> {
  30. public:
  31. virtual ~Channel();
  32. virtual void close() = 0;
  33. virtual bool send(message_variant data) = 0; // returns false if buffered
  34. virtual bool send(const byte *data, size_t size) = 0;
  35. virtual bool isOpen() const = 0;
  36. virtual bool isClosed() const = 0;
  37. virtual size_t maxMessageSize() const; // max message size in a call to send
  38. virtual size_t bufferedAmount() const; // total size buffered to send
  39. void onOpen(std::function<void()> callback);
  40. void onClosed(std::function<void()> callback);
  41. void onError(std::function<void(string error)> callback);
  42. void onMessage(std::function<void(message_variant data)> callback);
  43. void onMessage(std::function<void(binary data)> binaryCallback,
  44. std::function<void(string data)> stringCallback);
  45. void onBufferedAmountLow(std::function<void()> callback);
  46. void setBufferedAmountLowThreshold(size_t amount);
  47. // Extended API
  48. std::optional<message_variant> receive(); // only if onMessage unset
  49. std::optional<message_variant> peek(); // only if onMessage unset
  50. size_t availableAmount() const; // total size available to receive
  51. void onAvailable(std::function<void()> callback);
  52. protected:
  53. Channel(impl_ptr<impl::Channel> impl);
  54. };
  55. } // namespace rtc
  56. #endif // RTC_CHANNEL_H