#include #include #include #include #include #include #include "Socket.h" #include "Utils.h" Socket::Socket() : id(-1) { } Socket::~Socket() { if(id != -1 && close(id) == -1) { perror("cannot close socket"); } } bool Socket::start(uint16_t port) { id = socket(AF_INET, SOCK_STREAM, 0); if(id == -1) { perror("cannot create socket"); return true; } linger lin; lin.l_onoff = 1; lin.l_linger = 0; setsockopt(id, SOL_SOCKET, SO_LINGER, &lin, sizeof (lin)); struct sockaddr_in address; address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; address.sin_port = htons(port); if(bind(id, reinterpret_cast (&address), sizeof (sockaddr_in)) == -1) { perror("cannot bind socket"); return true; } if(listen(id, 10) == -1) { perror("cannot start listening on socket"); return true; } return false; } int Socket::waitForClients(int timeoutMillis) const { struct sockaddr_in clientAddress; socklen_t length = sizeof (sockaddr_in); int pollResult = Utils::pollFileDescriptor(id, timeoutMillis, "cannot poll socket"); if(pollResult <= 0) { return -1; } int clientId = accept(id, reinterpret_cast (&clientAddress), &length); if(clientId == -1) { perror("cannot accept client connection"); return -1; } return clientId; } bool Socket::readConsole(char* buffer, size_t bufferLength, int timeoutMillis) const { if(bufferLength == 0) { return false; } buffer[0] = '\0'; int pollResult = Utils::pollFileDescriptor(STDIN_FILENO, timeoutMillis, "cannot poll standard input"); if(pollResult <= 0) { return false; } size_t index = 0; while(index < bufferLength) { buffer[index] = getchar(); if(buffer[index] == '\n') { buffer[index] = '\0'; break; } index++; } return true; }