From 923912705998160b8cf2aa1b4c144d4f5d3e65fc Mon Sep 17 00:00:00 2001 From: cashmere Date: Thu, 25 Jun 2026 16:42:56 +0200 Subject: src/main.c: extract process message into seperate fn for readibility --- src/main.c | 55 ++++++++++++++++++++++++++++++++----------------------- 1 file changed, 32 insertions(+), 23 deletions(-) (limited to 'src') diff --git a/src/main.c b/src/main.c index fc2815a..99bda09 100644 --- a/src/main.c +++ b/src/main.c @@ -37,6 +37,35 @@ int handle_new_connection(int sfd, struct pollfd *fds, nfds_t *nfds) { return 0; } +int process_message(struct pollfd *fds, nfds_t *nfds) { + for (nfds_t i = 1; i < *nfds; i++) { + /* if client has something to say */ + if (fds[i].revents & POLLIN) { + char buffer[1024]; /* create a new empty buffer */ + ssize_t message = + read(fds[i].fd, buffer, + sizeof(buffer)); /* read the message which the client sent */ + /* if message of the client returns an error */ + if (message <= 0) { + /* close the connection if client disappeared or disconnected */ + close(fds[i].fd); + fds[i] = fds[*nfds - 1]; /* move back last slot */ + (*nfds)--; /* size down the current array */ + i--; + return -1; + } else { + /* send every message bytes to the other clients */ + for (nfds_t j = 1; j < *nfds; j++) { + if (j != i) { + write(fds[j].fd, buffer, message); + } + } + } + } + } + return 0; +} + int main() { struct sockaddr_in addr; addr.sin_family = AF_INET; /* IPv4 */ @@ -66,29 +95,9 @@ int main() { continue; } } - for (nfds_t i = 1; i < nfds; i++) { - /* if client has something to say */ - if (fds[i].revents & POLLIN) { - char buffer[1024]; /* create a new empty buffer */ - ssize_t message = - read(fds[i].fd, buffer, - sizeof(buffer)); /* read the message which the client sent */ - /* if message of the client returns an error */ - if (message <= 0) { - /* close the connection if client disappeared or disconnected */ - close(fds[i].fd); - fds[i] = fds[nfds - 1]; /* move back last slot */ - nfds--; /* size down the current array */ - i--; - } else { - /* send every message bytes to the other clients */ - for (nfds_t j = 1; j < nfds; j++) { - if (j != i) { - write(fds[j].fd, buffer, message); - } - } - } - } + if (process_message(fds, &nfds) == -1) { + perror("could not process message"); + continue; } } return 0; -- cgit v1.3.1