From b28f9e46e5e618b71925417fbd797cb03c203ffc Mon Sep 17 00:00:00 2001 From: "flyingscorpio@clevo" Date: Fri, 28 Oct 2022 10:12:17 +0200 Subject: [PATCH] Make client_sockid non blocking and handle the reading loops --- src/server.c | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/src/server.c b/src/server.c index 6e8e4dd..41fff8b 100644 --- a/src/server.c +++ b/src/server.c @@ -2,6 +2,8 @@ #include #include #include +#include +#include #include #include @@ -99,6 +101,8 @@ int main(int argc, char *argv[]) { } else { printf("received connection from %s\n", ip4tostring(ntohl(client_socket.sin_addr.s_addr))); + fcntl(client_sockid, F_SETFL, O_NONBLOCK); + /* Get client id to make sure we can handle him */ if ((client_id = get_next_free_client_id()) == -1) { /* Client array is full, refuse connection */ @@ -292,13 +296,11 @@ void *ClientListener(void *arg) { int n = 0; while (1) { - /* Loop for as long as there is nothing to read */ - while ((n = read(details.sockid, buf, BUF_LEN)) == 0); - if (n == -1) { - perror("read"); + /* Loop for as long as there is nothing to read (or there is an error) */ + while ((n = read(details.sockid, buf, BUF_LEN)) == -1) { + if (errno != EAGAIN) perror("read"); continue; } - /* TODO: Get mutex */ /* Write client_id for Dispatcher */ @@ -308,11 +310,8 @@ void *ClientListener(void *arg) { /* Write what we've read as long as there is something to read */ do { write(message_buffer[1], buf, n); - } while ((n = read(details.sockid, buf, BUF_LEN)) > 0); // TODO: we are blocking here, change socket details to make it non blocking? - if (n == -1) { - perror("read"); - continue; - } + } while ((n = read(details.sockid, buf, BUF_LEN)) > 0); + if ((n == -1) && (errno != EAGAIN)) perror("read"); /* TODO: Free mutex */ }