From 6f237888b1829eb34f022ec201e51a1cbf279604 Mon Sep 17 00:00:00 2001 From: ENGO150 Date: Fri, 24 Mar 2023 19:43:48 +0100 Subject: [PATCH] sending json formatted packet gonna make receiving decode this --- src/chat/misc.c | 53 +++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 51 insertions(+), 2 deletions(-) diff --git a/src/chat/misc.c b/src/chat/misc.c index 1a22038..ee3cc43 100644 --- a/src/chat/misc.c +++ b/src/chat/misc.c @@ -27,6 +27,8 @@ along with this program. If not, see . #include +#include + #include #include @@ -129,10 +131,55 @@ void *send_to_all(void *message) return NULL; } +void append(char **destination, char *key, char *value) +{ + char *output = why2_calloc(strlen(*destination) + strlen(key) + strlen(value) + 7, sizeof(char)); + + sprintf(output, "%s%s\"%s\":\"%s\"", *destination, strcmp(*destination, "") == 0 ? "" : ",", key, value); + + why2_deallocate(*destination); + + *destination = output; +} + +void add_brackets(char **json) +{ + char *output = why2_calloc(strlen(*json) + 3, sizeof(char)); + + sprintf(output, "{%s}", *json); + + why2_deallocate(*json); + + *json = output; +} + //GLOBAL void why2_send_socket(char *text, int socket) { - unsigned short text_length = (unsigned short) strlen(text) + 2; + char *output = why2_strdup(""); + size_t length_buffer = strlen(text); + char *text_copy = why2_calloc(length_buffer, sizeof(char)); + struct json_object *json = json_tokener_parse("{}"); + + //COPY text INTO text_copy WITHOUT LAST CHARACTER + strncpy(text_copy, text, length_buffer - 1); + + //ADD OBJECTS + json_object_object_add(json, "message", json_object_new_string(text_copy)); + json_object_object_add(json, "username", json_object_new_string("anon")); + + //GENERATE JSON STRING + json_object_object_foreach(json, key, value) + { + append(&output, key, (char*) json_object_get_string(value)); + } + add_brackets(&output); + + why2_deallocate(text_copy); + json_object_put(json); + + //printf("NEGR\n"); + unsigned short text_length = (unsigned short) strlen(output) + 2; char *final = why2_calloc(text_length, sizeof(char)); //SPLIT LENGTH INTO TWO CHARS @@ -141,13 +188,15 @@ void why2_send_socket(char *text, int socket) for (int i = 2; i < text_length; i++) //APPEND { - final[i] = text[i - 2]; + final[i] = output[i - 2]; } //SEND send(socket, final, text_length, 0); + //DEALLOCATION why2_deallocate(final); + why2_deallocate(output); } void *why2_communicate_thread(void *arg)