diff --git a/Server/Server.cpp b/Server/Server.cpp index 4609f3e..aa61cb6 100644 --- a/Server/Server.cpp +++ b/Server/Server.cpp @@ -6,7 +6,7 @@ /* By: iherman- #include +#include const int Server::kConnectionQueueLimit = 10; @@ -121,13 +122,43 @@ Server &Server::operator=(const Server& other) return *this; } +// TEMPORARY TESTING FUNCTION +void echo(User& client) +{ + std::string message = "Server received: " + client.getBuffer(); + send(client.getFd(), message.c_str(), message.size(), 0); +} + +void Server::parseCommand(User& client) +{ + std::stringstream args(client.getBuffer()); + std::string command; + + args >> command; + + std::map commands; + // TEMP + commands["echo"] = &echo; + + std::map::iterator it = commands.find(command); + if (it == commands.end()) + { + std::string message = "Error: command not found!"; + send(client.getFd(), message.c_str(), message.size(), 0); + client.clearBuffer(); + return ; + } + it->second(client); + client.clearBuffer(); +} + bool Server::handleClient(User& client) { const std::size_t kBufferSize = 1024; char buffer[kBufferSize] = {0}; int recv_amount = recv(client.getFd(), buffer, kBufferSize, 0); - + if (recv_amount == 0) return true; @@ -141,11 +172,7 @@ bool Server::handleClient(User& client) client.appendBuffer(std::string(buffer, recv_amount)); if (client.getBuffer().find('\n') != std::string::npos) - { - std::string message = "Server received: " + client.getBuffer(); - send(client.getFd(), message.c_str(), message.size(), 0); - client.clearBuffer(); - } + parseCommand(client); return false; } @@ -177,6 +204,16 @@ void Server::addClient() std::cout << "Client with fd: " << newClientSocket << " connected" << std::endl; } +std::vector::iterator Server::removeClient(std::vector::iterator& client) +{ + close(client->fd); + + std::cout << "Client with fd: " << client->fd << " disconnected " << std::endl; + + clients_.erase(client->fd); + return (sockets_.erase(client)); +} + void Server::run() { // add serverSocket_ to sockets_ @@ -197,7 +234,8 @@ void Server::run() { if (it->revents & (POLLERR | POLLHUP | POLLNVAL)) { - // remove client + it = removeClient(it); + continue ; } if (!(it->revents & POLLIN)) @@ -229,13 +267,7 @@ void Server::run() bool disconnected = handleClient(clientIt->second); if (disconnected) - { - close(it->fd); - std::cout << "Client with fd: " << it->fd << " disconnected " << std::endl; - - clients_.erase(it->fd); - it = sockets_.erase(it); - } + it = removeClient(it); else it++; } diff --git a/Server/Server.hpp b/Server/Server.hpp index 2b9000b..b21fb29 100644 --- a/Server/Server.hpp +++ b/Server/Server.hpp @@ -6,16 +6,13 @@ /* By: iherman- @@ -45,7 +42,9 @@ class Server bool handleClient(User& client); void addClient(); - std::vector::iterator removeClient(std::vector::iterator client); + std::vector::iterator removeClient(std::vector::iterator& client); + + void parseCommand(User& client); Server(const Server& other); Server &operator=(const Server& other);