aboutsummaryrefslogtreecommitdiff
path: root/common.c
diff options
context:
space:
mode:
authorRaymaekers Luca <raymaekers.luca@gmail.com>2024-10-21 00:12:02 +0200
committerRaymaekers Luca <raymaekers.luca@gmail.com>2024-10-21 00:12:02 +0200
commitd4e7c6876eed2733a2678668bdcabdd87659e826 (patch)
tree5943038b081f7392182542fc62b2ba2a9f8619bc /common.c
parentf6eef73f7f0e805811bb9c2d748c17d558615a74 (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 'common.c')
-rw-r--r--common.c61
1 files changed, 60 insertions, 1 deletions
diff --git a/common.c b/common.c
index 232cf64..34bed33 100644
--- a/common.c
+++ b/common.c
@@ -3,8 +3,10 @@
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
-#include <strings.h>
+#include <string.h>
#include <unistd.h>
+#include <sys/socket.h>
+
void writef(char *format, ...)
{
@@ -74,3 +76,60 @@ u8 load_message(struct message *msg, FILE *f)
return 0;
}
+
+u32 send_message(struct message msg, u32 serverfd)
+{
+ // stream length : message author : message timestamp : message text
+ u32 buf_len = sizeof(buf_len) + MESSAGE_AUTHOR_LEN + MESSAGE_TIMESTAMP_LEN + msg.len;
+ char buf[buf_len];
+ u32 offset;
+
+ memcpy(buf, &buf_len, sizeof(buf_len));
+ offset = sizeof(buf_len);
+ memcpy(buf + offset, msg.author, MESSAGE_AUTHOR_LEN);
+ offset += MESSAGE_AUTHOR_LEN;
+ memcpy(buf + offset, msg.timestamp, MESSAGE_TIMESTAMP_LEN);
+ offset += MESSAGE_TIMESTAMP_LEN;
+ memcpy(buf + offset, msg.text, msg.len);
+
+ u32 n = send(serverfd, &buf, buf_len, 0);
+ if (n == -1)
+ return n;
+
+ writef("%d bytes sent.\n", n);
+ return n;
+}
+
+u32 receive_message(struct message *msg, u32 clientfd)
+{
+ // must all be of the s
+ u32 nrecv, buf_len;
+ // limit on what can be received with recv()
+ u32 buf_size = 20;
+ // temporary buffer to receive message data over a stream
+ char recv_buf[BUF_MAX];
+
+ nrecv = recv(clientfd, recv_buf, buf_size, 0);
+ if (nrecv == 0 || nrecv == -1)
+ return nrecv;
+
+ memcpy(&buf_len, recv_buf, sizeof(buf_len));
+
+ u32 i = 0;
+ while (nrecv < buf_len) {
+ // advance the copying by the amounts of bytes received each time
+ i = recv(clientfd, recv_buf + nrecv, buf_size, 0);
+ if (i == 0 || i == -1)
+ return nrecv;
+ nrecv += i;
+ }
+
+ struct message received = {0};
+ memcpy(&received, recv_buf + sizeof(buf_len), MESSAGE_AUTHOR_LEN + MESSAGE_TIMESTAMP_LEN);
+ received.text = recv_buf + sizeof(buf_len) + MESSAGE_AUTHOR_LEN + MESSAGE_TIMESTAMP_LEN;
+ received.len = buf_len - sizeof(buf_len) - MESSAGE_AUTHOR_LEN - MESSAGE_TIMESTAMP_LEN;
+
+ // assume clientfd is serverfd + 1;
+ writef("Received %d bytes from client(%d): %s [%s] %s\n", nrecv, clientfd - 3, received.timestamp, received.author, received.text);
+ return nrecv;
+}