Client.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #include <iostream>
  2. #include <sys/socket.h>
  3. #include <arpa/inet.h>
  4. #include <cstring>
  5. #include <stdexcept>
  6. #include <unistd.h>
  7. #include <poll.h>
  8. #include "client/network/Client.h"
  9. #include "common/stream/Stream.h"
  10. Client::Client() {
  11. }
  12. Client::~Client() {
  13. if(connectionSocket != -1) {
  14. close(connectionSocket);
  15. }
  16. }
  17. bool Client::start(const string& ip, unsigned short port, IClientListener* listener) {
  18. connectionSocket = socket(AF_INET, SOCK_STREAM, 0);
  19. if(connectionSocket == -1) {
  20. throw runtime_error(string("cannot create socket: ") + strerror(errno));
  21. }
  22. struct sockaddr_in socketData;
  23. memset(&socketData, 0, sizeof (struct sockaddr_in));
  24. socketData.sin_family = AF_INET;
  25. socketData.sin_port = htons(port);
  26. if(inet_aton(ip.data(), &socketData.sin_addr) == 0) {
  27. throw runtime_error(ip + " is not a valid ip");
  28. }
  29. if(connect(connectionSocket, (struct sockaddr*) &socketData, sizeof (struct sockaddr_in)) == 0) {
  30. clientListener = listener;
  31. shouldRun = true;
  32. serverListenThread = thread(&Client::listenOnServer, this);
  33. return true;
  34. }
  35. return false;
  36. }
  37. void Client::stop() {
  38. shouldRun = false;
  39. serverListenThread.join();
  40. }
  41. void Client::listenOnServer() {
  42. struct pollfd fds;
  43. fds.fd = connectionSocket;
  44. fds.events = POLLIN;
  45. fds.revents = 0;
  46. clientListener->onServerJoin(connectionSocket);
  47. Stream st;
  48. while(shouldRun) {
  49. int pollData = poll(&fds, 1, 100);
  50. if(pollData > 0) {
  51. st.readSocket(connectionSocket);
  52. if(st.hasData()) {
  53. clientListener->onServerPackage(connectionSocket, st);
  54. } else {
  55. // server closed connection
  56. clientListener->onServerClose(connectionSocket);
  57. break;
  58. }
  59. } else if(pollData == -1) {
  60. cout << "poll error: " << strerror(errno) << endl;
  61. }
  62. }
  63. }