Made the commands_ map be a Server attribute

This commit is contained in:
iherman-
2026-05-12 20:02:32 +02:00
parent 644dbe92a8
commit 3578bd5b5c
2 changed files with 22 additions and 18 deletions

View File

@@ -6,7 +6,7 @@
/* By: iherman- <iherman-@student.42malaga.com +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2026/05/06 17:19:12 by iherman- #+# #+# */
/* Updated: 2026/05/11 20:34:33 by iherman- ### ########.fr */
/* Updated: 2026/05/12 19:25:29 by iherman- ### ########.fr */
/* */
/* ************************************************************************** */
@@ -35,6 +35,14 @@
const int Server::kConnectionQueueLimit = 10;
// TEMPORARY TESTING FUNCTION
void echo(User& client, std::istringstream& input)
{
std::string message = "Server received: " + input.str();
send(client.getFd(), message.c_str(), message.size(), 0);
}
Server::Server() :
port_(PORT_DEFAULT),
password_("password")
@@ -56,6 +64,8 @@ Server::Server() :
if (listen(serverSocket_, kConnectionQueueLimit))
throw std::runtime_error("Failed to listen");
std::cout << "Server port: " << port_
<< "\nServer Password: " << password_
<< std::endl;
@@ -96,6 +106,9 @@ Server::Server(int port, const std::string& password) :
if (listen(serverSocket_, kConnectionQueueLimit))
throw std::runtime_error("Failed to listen");
// Add all new commands to commands_ here
commands_["echo"] = &echo;
std::cout << "Server port: " << port_
<< "\nServer Password: " << password_
<< std::endl;
@@ -122,33 +135,22 @@ 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::istringstream args(client.getBuffer());
std::string command;
args >> command;
std::map<std::string, void (*)(User&)> commands;
// TEMP
commands["echo"] = &echo;
std::map<std::string, void (*)(User&)>::iterator it = commands.find(command);
if (it == commands.end())
std::map<std::string, void (*)(User&, std::istringstream&)>::iterator it = commands_.find(command);
if (it == commands_.end())
{
std::string message = "Error: command not found!";
std::string message = "Error: command not found!\n";
send(client.getFd(), message.c_str(), message.size(), 0);
client.clearBuffer();
return ;
}
it->second(client);
it->second(client, args);
client.clearBuffer();
}