diff --git a/src/chat/client/main.c b/src/chat/client/main.c index 5851412..a6e3f9e 100644 --- a/src/chat/client/main.c +++ b/src/chat/client/main.c @@ -18,6 +18,8 @@ along with this program. If not, see . #include +void send_socket(char *text, int socket); + int main(void) { int listen_socket = socket(AF_INET, SOCK_STREAM, 0); //CREATE SERVER SOCKET @@ -32,7 +34,27 @@ int main(void) if (connectStatus < 0) why2_die("Connecting failed."); - send(listen_socket, "test", 4, 0); + send_socket("123456789123456789", listen_socket); return 0; +} + +void send_socket(char *text, int socket) +{ + unsigned short text_length = (unsigned short) strlen(text); + char *final = why2_calloc(strlen(text) + 2, sizeof(char)); + + //SPLIT LENGTH INTO TWO CHARS + final[0] = (unsigned) text_length & 0xff; + final[1] = (unsigned) text_length >> 8; + + for (int i = 2; i < text_length + 2; i++) //APPEND + { + final[i] = text[i - 2]; + } + + //SEND + send(socket, final, text_length + 2, 0); + + why2_deallocate(final); } \ No newline at end of file diff --git a/src/chat/server/main.c b/src/chat/server/main.c index b0c2f92..09d341a 100644 --- a/src/chat/server/main.c +++ b/src/chat/server/main.c @@ -73,23 +73,21 @@ char *read_socket(int socket) return NULL; } - long content_size = 0; - char *content = NULL; + unsigned short content_size = 0; + char *content_buffer = why2_calloc(2, sizeof(char)); - //COUNT content_size - ioctl(socket, FIONREAD, &content_size); + //GET LENGTH + if (recv(socket, content_buffer, 2, 0) != 2) why2_die("Reading socket failed!"); - if (content_size == 0) - { - fprintf(stderr, "Reading socket failed."); - return NULL; - } + content_size = (unsigned short) (((unsigned) content_buffer[1] << 8) | content_buffer[0]); + + why2_deallocate(content_buffer); //ALLOCATE - content = why2_calloc(content_size + 1, sizeof(char)); + content_buffer = why2_calloc(content_size + 1, sizeof(char)); - //READ - if (recv(socket, content, content_size, 0) != content_size) why2_die("Reading socket failed!"); + //READ FINAL MESSAGE + if (recv(socket, content_buffer, content_size, 0) != content_size) why2_die("Reading socket failed!"); - return content; + return content_buffer; }