Implemented poll function for system

This commit is contained in:
aortigos
2026-04-15 00:06:09 +02:00
parent b39245ddf1
commit e46db9df57
2 changed files with 44 additions and 5 deletions

View File

@@ -44,12 +44,49 @@ int Server::run()
listen(server_fd, 1);
std::cout << "Esperando conexion" << std::endl;
int client_fd = accept(server_fd, NULL, NULL);
std::cout << "Cliente conectado" << std::endl;
std::vector<pollfd> fds;
char buf[512] = {0};
recv(client_fd, buf, sizeof(buf), 0);
std::cout << "Mensaje: " << buf << std::endl;
pollfd server_pfd;
server_pfd.fd = server_fd;
server_pfd.events = POLLIN;
server_pfd.revents = 0;
fds.push_back(server_pfd);
while (true)
{
poll(fds.data(), fds.size(), -1);
for(unsigned int i = 0; i < fds.size(); i++)
{
if (!(fds[i].revents & POLLIN))
continue ;
if (fds[i].fd == server_fd)
{
int client_fd = accept(server_fd, NULL, NULL);
std::cout << "Cliente conectado (fd=" << client_fd << ")\n";
pollfd client_pfd;
client_pfd.fd = client_fd;
client_pfd.events = POLLIN;
client_pfd.revents = 0;
fds.push_back(client_pfd);
} else {
char buf[512] = {0};
ssize_t n = recv(fds[i].fd, buf, sizeof(buf) - 1, 0);
if(n <= 0)
{
std::cout << "Cliente (fd=" << fds[i].fd << ") desconectado\n";
close(fds[i].fd);
fds.erase(fds.begin() + i);
i--;
} else {
std::cout << "Mensaje de fd=" << fds[i].fd << ": " << buf;
}
}
}
}
close(client_fd);
close(server_fd);