tcptransport.hpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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_TCP_TRANSPORT_H
  19. #define RTC_TCP_TRANSPORT_H
  20. #include "include.hpp"
  21. #include "queue.hpp"
  22. #include "transport.hpp"
  23. #if RTC_ENABLE_WEBSOCKET
  24. #include <mutex>
  25. #include <thread>
  26. // Use the socket defines from libjuice
  27. #include "../deps/libjuice/src/socket.h"
  28. namespace rtc {
  29. // Utility class to interrupt select()
  30. class SelectInterrupter {
  31. public:
  32. SelectInterrupter();
  33. ~SelectInterrupter();
  34. int prepare(fd_set &readfds, fd_set &writefds);
  35. void interrupt();
  36. private:
  37. std::mutex mMutex;
  38. #ifdef _WIN32
  39. socket_t mDummySock = INVALID_SOCKET;
  40. #else // assume POSIX
  41. int mPipeIn, mPipeOut;
  42. #endif
  43. };
  44. class TcpTransport : public Transport {
  45. public:
  46. TcpTransport(const string &hostname, const string &service, state_callback callback);
  47. ~TcpTransport();
  48. void start() override;
  49. bool stop() override;
  50. bool send(message_ptr message) override;
  51. void incoming(message_ptr message) override;
  52. bool outgoing(message_ptr message) override;
  53. private:
  54. void connect(const string &hostname, const string &service);
  55. void connect(const sockaddr *addr, socklen_t addrlen);
  56. void close();
  57. bool trySendQueue();
  58. bool trySendMessage(message_ptr &message);
  59. void runLoop();
  60. int prepareSelect(fd_set &readfds, fd_set &writefds);
  61. void interruptSelect();
  62. string mHostname, mService;
  63. socket_t mSock = INVALID_SOCKET;
  64. std::mutex mSockMutex;
  65. std::thread mThread;
  66. SelectInterrupter mInterrupter;
  67. Queue<message_ptr> mSendQueue;
  68. };
  69. } // namespace rtc
  70. #endif
  71. #endif