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

@@ -5,3 +5,5 @@ Client::Client() {}
Client::Client(int fd, std::string addr) : _fd(fd), _addr(addr) {} Client::Client(int fd, std::string addr) : _fd(fd), _addr(addr) {}
Client::~Client() {} Client::~Client() {}
int Client::getFd() const {return _fd;}

View File

@@ -12,6 +12,7 @@ class Client {
Client(int fd, std::string addr); Client(int fd, std::string addr);
~Client(); ~Client();
int getFd() const;
}; };
#endif #endif

View File

@@ -121,7 +121,7 @@ void Server::handleClientData(int fd) {
// Check if the client disconnected // Check if the client disconnected
if (bytes <= 0) { if (bytes <= 0) {
std::cout << "Client <" << fd << "> Disconnected" << std::endl; std::cout << "Client <" << fd << "> Disconnected" << std::endl;
// cleanups here clientCleanup(fd);
} else { } else {
buffer[bytes] = '\0'; buffer[bytes] = '\0';
std::cout << "Client <" << fd << "> Data: " << buffer; std::cout << "Client <" << fd << "> Data: " << buffer;
@@ -129,3 +129,19 @@ void Server::handleClientData(int fd) {
// parse, check, and handle the received data here // 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;
}
}
}

View File

@@ -33,6 +33,7 @@ class Server {
void addPollfd(int fd, short events, short revents); void addPollfd(int fd, short events, short revents);
void handleClientConnection(); void handleClientConnection();
void handleClientData(int fd); void handleClientData(int fd);
void clientCleanup(int fd);
}; };
#endif #endif