TcpListener.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. #include <iostream>
  2. #include <sys/types.h>
  3. #include <unistd.h>
  4. #include <netdb.h>
  5. #include <arpa/inet.h>
  6. #include <string.h>
  7. #include <string>
  8. #include "headers/TcpListener.h"
  9. #include "headers/constants.h"
  10. #include <sys/socket.h>
  11. int listening () {
  12. return socket(AF_INET, SOCK_STREAM, 0);
  13. }
  14. CTcpListener::CTcpListener(std::string ipAddress, int port, MessageReceivedHandler handler)
  15. : m_ipAddress(ipAddress), m_port(port), MessageReceived(handler) {
  16. }
  17. // destructor
  18. CTcpListener::~CTcpListener() {
  19. cleanup();
  20. }
  21. // Send message to client
  22. void CTcpListener::sendMessage(int clientSocket, std::string msg) {
  23. send(clientSocket, msg.c_str(), msg.size() +1, 0);
  24. }
  25. // Initialize
  26. bool CTcpListener::init() {
  27. std::cout << "Initializing socket listener" << std::endl;
  28. return true;
  29. }
  30. // Main process loop
  31. void CTcpListener::run() {
  32. char* buf[MAX_BUFFER_SIZE];
  33. while (true) {
  34. int listening = createSocket();
  35. if (listening == SOCKET_ERROR) {
  36. std::cout << "Socket error: shutting down server" << std::endl;
  37. break;
  38. }
  39. int socket = waitForConnection(listening);
  40. if (socket != SOCKET_ERROR) {
  41. close(listening);
  42. while (true) {
  43. memset(buf, 0, MAX_BUFFER_SIZE);
  44. int bytesReceived = 0;
  45. bytesReceived = recv(socket, buf, MAX_BUFFER_SIZE, 0);
  46. if (bytesReceived > 0) {
  47. const char* constString = (const char*) buf;
  48. std::cout << "Received: " << constString << std::endl;
  49. MessageReceived(this, socket, std::string(constString));
  50. } else {
  51. std::cout << "client disconnected" << std::endl;
  52. break;
  53. }
  54. }
  55. close(socket);
  56. }
  57. }
  58. }
  59. // Cleanup
  60. void CTcpListener::cleanup() {
  61. std::cout << "Cleaning up" << std::endl;
  62. }
  63. int CTcpListener::createSocket() {
  64. int listening = socket(AF_INET, SOCK_STREAM, 0);
  65. if (listening != SOCKET_ERROR) {
  66. sockaddr_in hint;
  67. hint.sin_family = AF_INET;
  68. hint.sin_port = htons(m_port);
  69. inet_pton(AF_INET, m_ipAddress.c_str(), &hint.sin_addr);
  70. int bindOk = bind(listening, (sockaddr*)&hint, sizeof(hint));
  71. if (bindOk != SOCKET_ERROR) {
  72. int listenOk = listen(listening, SOMAXCONN);
  73. if (listenOk == SOCKET_ERROR) {
  74. return -1;
  75. }
  76. } else {
  77. return -1;
  78. }
  79. }
  80. return listening;
  81. }
  82. int CTcpListener::waitForConnection(int listening) {
  83. int client = accept(listening, NULL, NULL);
  84. return client;
  85. }