Socket.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #include <iostream>
  2. #include <sys/types.h>
  3. #include <sys/socket.h>
  4. #include <unistd.h>
  5. #include <netinet/in.h>
  6. #include <vector>
  7. #include "Socket.h"
  8. #include "Utils.h"
  9. Socket::Socket() : id(-1) {
  10. }
  11. Socket::~Socket() {
  12. if(id != -1 && close(id) == -1) {
  13. perror("cannot close socket");
  14. }
  15. }
  16. bool Socket::start(uint16_t port) {
  17. id = socket(AF_INET, SOCK_STREAM, 0);
  18. if(id == -1) {
  19. perror("cannot create socket");
  20. return true;
  21. }
  22. linger lin;
  23. lin.l_onoff = 1;
  24. lin.l_linger = 0;
  25. setsockopt(id, SOL_SOCKET, SO_LINGER, &lin, sizeof (lin));
  26. struct sockaddr_in address;
  27. address.sin_family = AF_INET;
  28. address.sin_addr.s_addr = INADDR_ANY;
  29. address.sin_port = htons(port);
  30. if(bind(id, reinterpret_cast<sockaddr*> (&address), sizeof (sockaddr_in)) == -1) {
  31. perror("cannot bind socket");
  32. return true;
  33. }
  34. if(listen(id, 10) == -1) {
  35. perror("cannot start listening on socket");
  36. return true;
  37. }
  38. return false;
  39. }
  40. int Socket::waitForClients(int timeoutMillis) const {
  41. struct sockaddr_in clientAddress;
  42. socklen_t length = sizeof (sockaddr_in);
  43. int pollResult = Utils::pollFileDescriptor(id, timeoutMillis, "cannot poll socket");
  44. if(pollResult <= 0) {
  45. return -1;
  46. }
  47. int clientId = accept(id, reinterpret_cast<sockaddr*> (&clientAddress), &length);
  48. if(clientId == -1) {
  49. perror("cannot accept client connection");
  50. return -1;
  51. }
  52. return clientId;
  53. }
  54. bool Socket::readConsole(char* buffer, size_t bufferLength, int timeoutMillis) const {
  55. if(bufferLength == 0) {
  56. return false;
  57. }
  58. buffer[0] = '\0';
  59. int pollResult = Utils::pollFileDescriptor(STDIN_FILENO, timeoutMillis, "cannot poll standard input");
  60. if(pollResult <= 0) {
  61. return false;
  62. }
  63. size_t index = 0;
  64. while(index < bufferLength) {
  65. buffer[index] = getchar();
  66. if(buffer[index] == '\n') {
  67. buffer[index] = '\0';
  68. break;
  69. }
  70. index++;
  71. }
  72. return true;
  73. }