diff options
Diffstat (limited to 'src/main.c')
| -rw-r--r-- | src/main.c | 55 |
1 files changed, 32 insertions, 23 deletions
@@ -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; |
