Waits for incoming requests, which are null terminated If the client's connection is closed, the current message length will be -1, hence the server can be stopped When a request is received, parse it as JSON, run the corresponding effect if no incompatible effects are currently running If the effect was started, it sends a Response with code 0 (Success), otherwise it sends a Response wi
| 86 | /// If the effect was started, it sends a Response with code 0 (Success), otherwise it sends a Response with code 3 (Retry) |
| 87 | /// </summary> |
| 88 | void ClientLoop() { |
| 89 | LOG_INFO("Starting crowd control client loop" << std::endl); |
| 90 | |
| 91 | int currentMessageLength = 0; |
| 92 | int bytesRead = 0; |
| 93 | char buffer[1024]; |
| 94 | |
| 95 | while (!GameState::GameClosing) { |
| 96 | //Receive command |
| 97 | currentMessageLength = 0; |
| 98 | |
| 99 | do { |
| 100 | //Read one byte at a time until null byte is read |
| 101 | if (currentMessageLength >= sizeof(buffer)) { |
| 102 | LOG_ERROR("Current message is longer than buffer size" << std::endl); |
| 103 | return; |
| 104 | } |
| 105 | |
| 106 | //Read 1 byte from socket |
| 107 | bytesRead = recv(sock, buffer + currentMessageLength, 1, NULL); |
| 108 | |
| 109 | //If last byte was null byte, exit recv loop |
| 110 | if (bytesRead > 0 && buffer[currentMessageLength] == NULL) break; |
| 111 | |
| 112 | currentMessageLength += bytesRead; |
| 113 | } while (bytesRead > 0); |
| 114 | |
| 115 | if (currentMessageLength == -1) { //Usually happens when the connection closes (i.e. when the server is down) |
| 116 | serverStarted = false; |
| 117 | break; |
| 118 | } |
| 119 | |
| 120 | //Parse command |
| 121 | std::string command = std::string(&buffer[0], &buffer[currentMessageLength]); |
| 122 | |
| 123 | json j = json::parse(command); |
| 124 | |
| 125 | LOG_INFO("Received command:" << std::endl); |
| 126 | LOG_INFO(j.dump(2) << std::endl); |
| 127 | |
| 128 | Request request; |
| 129 | CrowdControl::Structs::from_json_request(j, request); |
| 130 | |
| 131 | //Run command |
| 132 | LOG_INFO("Running command" << std::endl); |
| 133 | const Response response = RunCommand(request); |
| 134 | |
| 135 | //Respond |
| 136 | LOG_INFO("Responding to command" << std::endl); |
| 137 | |
| 138 | SendResponse(response); |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | /// <summary> |
| 143 | /// Opens a TCP socket on localhost, port 45659 |
no test coverage detected