1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- #include <iostream>
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <unistd.h>
- #include <netinet/in.h>
- #include <vector>
- #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<sockaddr*> (&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<sockaddr*> (&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;
- }
|