diff options
author | Raymaekers Luca <raymaekers.luca@gmail.com> | 2024-10-21 00:12:02 +0200 |
---|---|---|
committer | Raymaekers Luca <raymaekers.luca@gmail.com> | 2024-10-21 00:12:02 +0200 |
commit | d4e7c6876eed2733a2678668bdcabdd87659e826 (patch) | |
tree | 5943038b081f7392182542fc62b2ba2a9f8619bc /server.c | |
parent | f6eef73f7f0e805811bb9c2d748c17d558615a74 (diff) |
Added common code for messages
- add: send_message, receive_message functions
- change: use u8, u16, u32, where possible
- fix: use PORT in server.c
Diffstat (limited to 'server.c')
-rw-r--r-- | server.c | 34 |
1 files changed, 17 insertions, 17 deletions
@@ -5,6 +5,7 @@ #include <poll.h> #include <stdio.h> #include <stdlib.h> +#include <string.h> #include <sys/socket.h> #include <unistd.h> @@ -14,7 +15,7 @@ static const char *filename = "history.dat"; enum { FD_SERVER = 0 }; -int serverfd; +u32 serverfd; void err_exit(const char *msg) { @@ -27,9 +28,9 @@ void err_exit(const char *msg) int main(void) { - int clientfd; - int nclient = 0; - int on = 1; + u32 clientfd; + u16 nclient = 0; + u8 on = 1; struct message msg_recv = {0}; serverfd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, IPPROTO_TCP); @@ -38,7 +39,7 @@ int main(void) const struct sockaddr_in address = { AF_INET, - htons(9999), + htons(PORT), {0}, }; @@ -60,7 +61,7 @@ int main(void) }; for (;;) { - int ret = poll(fds, FD_MAX, 50000); + u32 ret = poll(fds, FD_MAX, 50000); if (ret == -1) err_exit("Error while polling"); else if (ret == 0) { @@ -85,7 +86,7 @@ int main(void) nclient++; // get a new available spot in the fds array - int i; + u32 i; for (i = 0; i < MAX_CONNECTIONS; i++) if (fds[i].fd == -1) break; @@ -98,15 +99,15 @@ int main(void) } // Check for events on connected clients - for (int i = 1; i <= nclient; i++) { + for (u32 i = 1; i <= nclient; i++) { if (!(fds[i].revents & POLLIN)) continue; - int nrecv; + u32 nrecv; clientfd = fds[i].fd; - nrecv = recv(clientfd, &msg_recv, sizeof(struct message), 0); + nrecv = receive_message(&msg_recv, clientfd); if (nrecv == 0) { printf("client %d disconnected.\n", i); fds[i].fd = -1; @@ -122,10 +123,8 @@ int main(void) err_exit("Error while receiving from client socket."); } - printf("client %d sent %d bytes.\n", i, nrecv); - // TODO: - for (int j = 1; j <= nclient; j++) { + for (u32 j = 1; j <= nclient; j++) { // skip the client that sent the message if (j == i) continue; @@ -136,10 +135,11 @@ int main(void) } // // TODO: Serialize received message - FILE *f = fopen(filename, "wb"); - save_message(&msg_recv, f); - fclose(f); - // return 0; + // FILE *f = fopen(filename, "wb"); + // save_message(&msg_recv, f); + // fclose(f); + // // return 0; + } } |