socket_listener.h 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. #ifndef __SOCKET_LISTENER_H__
  2. #define __SOCKET_LISTENER_H__
  3. // Project libraries
  4. #include "send_interface.h"
  5. #include "types.h"
  6. // System libraries
  7. #include <sys/socket.h>
  8. // C++ Libraries
  9. #include <atomic>
  10. #include <condition_variable>
  11. #include <functional>
  12. #include <iostream>
  13. #include <memory>
  14. #include <mutex>
  15. #include <queue>
  16. #include <string>
  17. #include <thread>
  18. #include <vector>
  19. class SocketListener : public SendInterface {
  20. public:
  21. class MessageHandler {
  22. public:
  23. MessageHandler(std::function<void()> cb) : m_cb(cb) {}
  24. void operator()() { m_cb(); }
  25. private:
  26. std::function<void()> m_cb;
  27. };
  28. // constructor
  29. SocketListener(std::string ipAddress, int port);
  30. // destructor
  31. ~SocketListener();
  32. /**
  33. * Send a message to a client socket described by its file descriptor
  34. * @param[in] {int} client_socket_fd The client socket file descriptor
  35. * @param[in] {std::string} The message to be sent
  36. */
  37. virtual void sendMessage(int client_socket_fd,
  38. std::shared_ptr<char[]> buffer) override;
  39. MessageHandler createMessageHandler(std::function<void()> cb);
  40. /**
  41. * Perform intialization work
  42. */
  43. bool init();
  44. /**
  45. * Main message loop
  46. */
  47. void run();
  48. /**
  49. * Perform any cleanup work
  50. */
  51. void cleanup();
  52. // virtual void setMessageHandler(MessageHandler message_handler) override;
  53. private:
  54. // private methods
  55. int createSocket();
  56. int waitForConnection(int listening);
  57. void loop_check();
  58. void done();
  59. void handle_loop();
  60. void detachThreads();
  61. void push_to_queue(std::function<void()> fn);
  62. void handle_client_socket(int client_socket_fd,
  63. SocketListener::MessageHandler message_handler,
  64. std::shared_ptr<char[]> buf);
  65. // private members
  66. std::string m_ip_address;
  67. int m_port;
  68. std::thread m_loop_thread;
  69. std::queue<std::function<void()>> task_queue;
  70. std::mutex m_mutex_lock;
  71. std::condition_variable pool_condition;
  72. std::atomic<bool> accepting_tasks;
  73. std::atomic<bool> shutdown_loop;
  74. std::atomic<bool> m_loop_switch;
  75. std::vector<std::thread> thread_pool;
  76. };
  77. #endif // __SOCKET_LISTENER_H__