socket_listener.hpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #ifndef __SOCKET_LISTENER_H__
  2. #define __SOCKET_LISTENER_H__
  3. // Project libraries
  4. #include "send_interface.hpp"
  5. #include "task_queue.hpp"
  6. #include "types.hpp"
  7. // System libraries
  8. #include <sys/socket.h>
  9. // C++ Libraries
  10. #include <functional>
  11. #include <iostream>
  12. #include <memory>
  13. #include <string>
  14. #include <vector>
  15. class SocketListener : public SendInterface {
  16. public:
  17. class MessageHandler {
  18. public:
  19. MessageHandler(std::function<void()> cb) : m_cb(cb) {}
  20. void operator()() { m_cb(); }
  21. private:
  22. std::function<void()> m_cb;
  23. };
  24. // constructor
  25. SocketListener(int arg_num, char** args);
  26. // destructor
  27. ~SocketListener();
  28. /**
  29. * Send a message to a client socket described by its file descriptor
  30. * @param[in] {int} client_socket_fd The client socket file descriptor
  31. * @param[in] {std::string} The message to be sent
  32. */
  33. virtual void sendMessage(int client_socket_fd,
  34. std::weak_ptr<char[]> w_buffer_ptr) override;
  35. MessageHandler createMessageHandler(std::function<void()> cb);
  36. /**
  37. * Perform intialization work
  38. */
  39. bool init();
  40. /**
  41. * Main message loop
  42. */
  43. void run();
  44. /**
  45. * Perform any cleanup work
  46. */
  47. void cleanup();
  48. // virtual void setMessageHandler(MessageHandler message_handler) override;
  49. private:
  50. // private methods
  51. int createSocket();
  52. int waitForConnection(int listening);
  53. void handleClientSocket(int client_socket_fd,
  54. SocketListener::MessageHandler message_handler,
  55. const std::shared_ptr<char[]>& s_buffer_ptr);
  56. /* private members */
  57. // Server arguments
  58. std::string m_ip_address;
  59. int m_port;
  60. std::unique_ptr<TaskQueue> u_task_queue_ptr;
  61. };
  62. #endif // __SOCKET_LISTENER_H__