diff options
| author | cashmere <cashmere@autistici.org> | 2026-06-22 19:52:39 +0200 |
|---|---|---|
| committer | cashmere <cashmere@autistici.org> | 2026-06-22 19:52:39 +0200 |
| commit | 764f4ea337f9c0143b77110c82d8f9d7e98ab1ca (patch) | |
| tree | 6dd8954f6edc9b5197e71dab47dfa86be44b8861 /src | |
| parent | 3f755f01deaa7e4dfe7fde2272056ba4a1c67eb5 (diff) | |
| download | telnet-764f4ea337f9c0143b77110c82d8f9d7e98ab1ca.tar.gz | |
src/main.c: broadcast messages to all connected clients
Diffstat (limited to 'src')
| -rw-r--r-- | src/main.c | 35 |
1 files changed, 31 insertions, 4 deletions
@@ -38,10 +38,37 @@ int main() { perror("could not run poll"); return 1; } - char buf[1024]; - ssize_t n; - while ((n = read(conn, buf, sizeof(buf))) > 0) { - write(conn, buf, n); + if (fds[0].revents & POLLIN) { + /* we accept the connections */ + int conn = accept(sfd, NULL, NULL); + if (conn == -1) { + perror("could not accept connection"); + continue; /* if one client is not able to connect the server shall not + die */ + } + fds[nfds].fd = conn; /* read */ + fds[nfds].events = + POLLIN; /* check if telnet client has something to say */ + nfds++; + } + for (nfds_t i = 1; i < nfds; i++) { + /* if client has something to say */ + if (fds[i].revents & POLLIN) { + char buf[1024]; + ssize_t n = read(fds[i].fd, buf, + sizeof(buf)); /* read the n which the client sent */ + if (n <= 0) { + /* close the connection if client disappeared or disconnected */ + close(fds[i].fd); + } else { + /* send every n bytes to the other clients */ + for (nfds_t j = 1; j < nfds; j++) { + if (j != i) { + write(fds[j].fd, buf, n); + } + } + } + } } } return 0; |
