1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- #include <iostream>
- #include <cstring>
- #include <unistd.h>
- #include <sys/socket.h>
- #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;
- game.parse(buffer, output);
- 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;
- }
|