Files
irc/Server/Server.cpp

129 lines
3.0 KiB
C++

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Server.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: aortigos <aortigos@student.42malaga.com> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2026/04/13 22:31:44 by aortigos #+# #+# */
/* Updated: 2026/04/13 22:31:44 by aortigos ### ########.fr */
/* */
/* ************************************************************************** */
#include "Server.hpp"
//////////////////
// Constructors //
//////////////////
Server::Server()
{
std::cout << "Server default constructor called" << std::endl;
}
Server::Server(int port, std::string password)
: port(port), password(password), server_fd(-1)
{
server_fd = socket(AF_INET, SOCK_STREAM, 0);
if (server_fd < 0)
throw std::runtime_error("Error: socket()");
int opt = 1;
setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
sockaddr_in addr = {};
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = INADDR_ANY;
if (bind(server_fd, (sockaddr*)&addr, sizeof(addr)) < 0)
throw std::runtime_error("Error: bind()");
if (listen(server_fd, 10) < 0)
throw std::runtime_error("Error: listen()");
pollfd server_pfd;
server_pfd.fd = server_fd;
server_pfd.events = POLLIN;
server_pfd.revents = 0;
fds.push_back(server_pfd);
std::cout << "Server will use port: " << port << std::endl;
}
Server::~Server()
{
std::cout << "Server destructor called" << std::endl;
}
int Server::run()
{
while (true)
{
poll(this->fds.data(), this->fds.size(), -1);
for(unsigned int i = 0; i < this->fds.size(); i++)
{
if (!(this->fds[i].revents & POLLIN))
continue ;
if (this->fds[i].fd == server_fd)
acceptClient();
else
readClient(this->fds[i].fd);
}
}
return (0);
}
void Server::acceptClient()
{
int client_fd = accept(server_fd, NULL, NULL);
if (client_fd < 0)
return ;
// Añadimos al poll
pollfd client_pfd;
client_pfd.fd = client_fd;
client_pfd.events = POLLIN;
client_pfd.revents = 0;
fds.push_back(client_pfd);
clients.insert(std::make_pair(client_fd, Client(client_fd)));
std::cout << "Nuevo cliente (fd=" << client_fd << ")\n";
}
void Server::readClient(int fd)
{
char buf[512] = {0};
int r = recv(fd, buf, sizeof(buf) - 1, 0);
if (r <= 0)
{
removeClient(fd);
return ;
}
clients[fd].appendBuffer(buf);
std::cout << "fd=" << fd << " dice: " << buf;
}
void Server::removeClient(int fd)
{
std::cout << "Cliente (fd=" << fd << ") desconectado\n";
for (size_t i = 0; i < fds.size(); i++)
{
if (fds[i].fd == fd)
{
fds.erase(fds.begin() + i);
break ;
}
}
clients.erase(fd);
close(fd);
}