socket_listener.hpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. void sendMessage(int client_socket_fd, char* message, bool short_message);
  36. void sendMessage(int client_socket_fd, char* message, size_t size);
  37. void sendMessage(int client_socket_fd, const char* message, size_t size);
  38. MessageHandler createMessageHandler(std::function<void()> cb);
  39. /**
  40. * Perform intialization work
  41. */
  42. bool init();
  43. /**
  44. * Main message loop
  45. */
  46. void run();
  47. /**
  48. * Perform any cleanup work
  49. */
  50. void cleanup();
  51. // virtual void setMessageHandler(MessageHandler message_handler) override;
  52. private:
  53. // private methods
  54. int createSocket();
  55. virtual void onMessageReceived(int client_socket_fd,
  56. std::weak_ptr<char[]> w_buffer_ptr);
  57. int waitForConnection(int listening);
  58. void handleClientSocket(int client_socket_fd,
  59. SocketListener::MessageHandler message_handler,
  60. const std::shared_ptr<char[]>& s_buffer_ptr);
  61. /* private members */
  62. // Server arguments
  63. std::string m_ip_address;
  64. int m_port;
  65. std::unique_ptr<TaskQueue> u_task_queue_ptr;
  66. };
  67. #endif // __SOCKET_LISTENER_H__