added content length to first two bytes of sent text in why2-chat

This commit is contained in:
Václav Šmejkal 2023-02-20 12:27:50 +01:00
parent 3a4f5ed7b6
commit 6687d6e622
Signed by: ENGO150
GPG Key ID: F6D6DF86242C5A59
2 changed files with 34 additions and 14 deletions

View File

@ -18,6 +18,8 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <why2/chat/common.h>
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);
}

View File

@ -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;
}