socket_listener.hpp 2.0 KB

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