#include #include #include #include #include "Client.h" #include "Utils.h" void nothing() { } Client::Client() : id(-1), thread(nothing) { } Client::~Client() { closeSocket(); if(thread.joinable()) { thread.join(); } } bool Client::isFree() const { return id == -1; } void Client::sendString(const char* buffer) const { send(id, buffer, strlen(buffer), 0); } void Client::start(int clientId) { id = clientId; if(thread.joinable()) { thread.join(); } thread = std::thread(&Client::loop, this); } void Client::loop() { String s; game.reset(s); sendString(s); while(true) { int pollResult = Utils::pollFileDescriptor(id, 100, "cannot poll client socket"); if(pollResult < 0) { break; } else if(pollResult == 0) { continue; } String buffer; if(buffer.receiveFromSocket(id)) { break; } String output; if(game.parse(buffer, output)) { sendString(output); break; } sendString(output); } std::cout << "client removed\n"; closeSocket(); } void Client::onReceive(char* buffer) { std::cout << buffer << "\n"; } void Client::closeSocket() { if(id != -1 && close(id) == -1) { perror("cannot close client socket"); } id = -1; }