Client.cpp 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #include <iostream>
  2. #include <cstring>
  3. #include <unistd.h>
  4. #include <sys/socket.h>
  5. #include "Client.h"
  6. #include "Utils.h"
  7. void nothing() {
  8. }
  9. Client::Client() : id(-1), thread(nothing) {
  10. }
  11. Client::~Client() {
  12. closeSocket();
  13. if(thread.joinable()) {
  14. thread.join();
  15. }
  16. }
  17. bool Client::isFree() const {
  18. return id == -1;
  19. }
  20. void Client::sendString(const char* buffer) const {
  21. send(id, buffer, strlen(buffer), 0);
  22. }
  23. void Client::start(int clientId) {
  24. id = clientId;
  25. if(thread.joinable()) {
  26. thread.join();
  27. }
  28. thread = std::thread(&Client::loop, this);
  29. }
  30. void Client::loop() {
  31. String s;
  32. game.reset(s);
  33. sendString(s);
  34. while(true) {
  35. int pollResult = Utils::pollFileDescriptor(id, 100, "cannot poll client socket");
  36. if(pollResult < 0) {
  37. break;
  38. } else if(pollResult == 0) {
  39. continue;
  40. }
  41. String buffer;
  42. if(buffer.receiveFromSocket(id)) {
  43. break;
  44. }
  45. String output;
  46. game.parse(buffer, output);
  47. sendString(output);
  48. }
  49. std::cout << "client removed\n";
  50. closeSocket();
  51. }
  52. void Client::onReceive(char* buffer) {
  53. std::cout << buffer << "\n";
  54. }
  55. void Client::closeSocket() {
  56. if(id != -1 && close(id) == -1) {
  57. perror("cannot close client socket");
  58. }
  59. id = -1;
  60. }