From 454e32f59000737787a156a1aa3095c10ec55a25 Mon Sep 17 00:00:00 2001 From: bettercallous Date: Tue, 9 Apr 2024 03:09:14 +0000 Subject: [PATCH] fixed infinite loop when a client disconnects (remove and clean disconnected clients) --- Client.cpp | 2 ++ Client.hpp | 1 + Server.cpp | 18 +++++++++++++++++- Server.hpp | 1 + 4 files changed, 21 insertions(+), 1 deletion(-) diff --git a/Client.cpp b/Client.cpp index fe3b1c6..745a8d7 100644 --- a/Client.cpp +++ b/Client.cpp @@ -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;} diff --git a/Client.hpp b/Client.hpp index b9d1711..2f17c0a 100644 --- a/Client.hpp +++ b/Client.hpp @@ -12,6 +12,7 @@ class Client { Client(int fd, std::string addr); ~Client(); + int getFd() const; }; #endif \ No newline at end of file diff --git a/Server.cpp b/Server.cpp index 2adddda..6cdaf4e 100644 --- a/Server.cpp +++ b/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::iterator it = _fds.begin(); it != _fds.end(); ++it) { + if (it->fd == fd) { + _fds.erase(it); + break; + } + } + + for (std::vector::iterator it = _clients.begin(); it != _clients.end(); ++it) { + if (it->getFd() == fd) { + _clients.erase(it); + break; + } + } +} diff --git a/Server.hpp b/Server.hpp index 4685ea8..b50acc5 100644 --- a/Server.hpp +++ b/Server.hpp @@ -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 \ No newline at end of file