fixed infinite loop when a client disconnects (remove and clean disconnected clients)
This commit is contained in:
@@ -5,3 +5,5 @@ Client::Client() {}
|
||||
Client::Client(int fd, std::string addr) : _fd(fd), _addr(addr) {}
|
||||
|
||||
Client::~Client() {}
|
||||
|
||||
int Client::getFd() const {return _fd;}
|
||||
|
@@ -12,6 +12,7 @@ class Client {
|
||||
Client(int fd, std::string addr);
|
||||
~Client();
|
||||
|
||||
int getFd() const;
|
||||
};
|
||||
|
||||
#endif
|
18
Server.cpp
18
Server.cpp
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -33,6 +33,7 @@ class Server {
|
||||
void addPollfd(int fd, short events, short revents);
|
||||
void handleClientConnection();
|
||||
void handleClientData(int fd);
|
||||
void clientCleanup(int fd);
|
||||
};
|
||||
|
||||
#endif
|
Reference in New Issue
Block a user