pollservice.hpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /**
  2. * Copyright (c) 2022 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_IMPL_POLL_SERVICE_H
  19. #define RTC_IMPL_POLL_SERVICE_H
  20. #include "pollinterrupter.hpp"
  21. #include "socket.hpp"
  22. #include "common.hpp"
  23. #include "internals.hpp"
  24. #if RTC_ENABLE_WEBSOCKET
  25. #include <chrono>
  26. #include <mutex>
  27. #include <thread>
  28. #include <unordered_map>
  29. #include <functional>
  30. namespace rtc::impl {
  31. class PollService {
  32. public:
  33. using clock = std::chrono::steady_clock;
  34. static PollService &Instance();
  35. PollService(const PollService &) = delete;
  36. PollService &operator=(const PollService &) = delete;
  37. PollService(PollService &&) = delete;
  38. PollService &operator=(PollService &&) = delete;
  39. void start();
  40. void join();
  41. enum class Direction { Both, In, Out };
  42. enum class Event { None, Error, Timeout, In, Out };
  43. struct Params {
  44. Direction direction;
  45. optional<clock::duration> timeout;
  46. std::function<void(Event)> callback;
  47. };
  48. void add(socket_t sock, Params params);
  49. void remove(socket_t sock);
  50. private:
  51. PollService();
  52. ~PollService();
  53. void prepare(std::vector<struct pollfd> &pfds, optional<clock::time_point> &next);
  54. void process(std::vector<struct pollfd> &pfds);
  55. void runLoop();
  56. struct SocketEntry {
  57. Params params;
  58. optional<clock::time_point> until;
  59. };
  60. using SocketMap = std::unordered_map<socket_t, SocketEntry>;
  61. unique_ptr<SocketMap> mSocks;
  62. std::recursive_mutex mMutex;
  63. std::thread mThread;
  64. bool mStopped;
  65. PollInterrupter mInterrupter;
  66. };
  67. std::ostream &operator<<(std::ostream &out, PollService::Direction direction);
  68. } // namespace rtc::impl
  69. #endif
  70. #endif