fixed infinite loop when a client disconnects (remove and clean disconnected clients)

This commit is contained in:
bettercallous
2024-04-09 03:09:14 +00:00
parent 3006bfa5e2
commit 454e32f590
4 changed files with 21 additions and 1 deletions

View File

@@ -121,7 +121,7 @@ void Server::handleClientData(int fd) {
// Check if the client disconnected
if (bytes <= 0) {
std::cout << "Client <" << fd << "> Disconnected" << std::endl;
// cleanups here
clientCleanup(fd);
} else {
buffer[bytes] = '\0';
std::cout << "Client <" << fd << "> Data: " << buffer;
@@ -129,3 +129,19 @@ void Server::handleClientData(int fd) {
// parse, check, and handle the received data here
}
}
void Server::clientCleanup(int fd) {
for (std::vector<pollfd>::iterator it = _fds.begin(); it != _fds.end(); ++it) {
if (it->fd == fd) {
_fds.erase(it);
break;
}
}
for (std::vector<Client>::iterator it = _clients.begin(); it != _clients.end(); ++it) {
if (it->getFd() == fd) {
_clients.erase(it);
break;
}
}
}