I know that TCP is a data stream protocol and that packets arrive at their destination complete and in order but with no indication of where one packet ends and another begins. I've been trying to work around the problem of getting "merged" or "split" packets on the server.
I'm using a function similar to the sendall() function that Beej uses in his guide, however my packets are still arriving split.
Here's my sending function:
int sendAll(TCPsocket socket, char *buff, unsigned short len)
{
unsigned short total = 0;
unsigned short bytesleft = len;
int n;
n = SDLNet_TCP_Send(socket, &len, sizeof(short));
while (total < len)
{
n = SDLNet_TCP_Send(socket, buff, bytesleft);
if (n == -1) { break; }
total += n;
bytesleft -= n;
}
return n == -1?-1:0;
}
And my receiving function
int recvAll(TCPsocket socket, char *buff)
{
unsigned short total = 0;
unsigned short len = 0;
int n;
n = SDLNet_TCP_Recv(socket, &len, sizeof(short));
unsigned short bytesleft = len;
while (total < len)
{
n = SDLNet_TCP_Recv(socket, buff, bytesleft);
if (n == -1) { break; }
total += n;
bytesleft -= n;
}
return n == -1?-1:0; // Return -1 on failure, 0 on success;
}
I first send/recv an unsigned short denoting the length of the message, and then I make repeated calls to send/recv until at least that many bytes has been received. I then print the output to the screen.
I'm unsure as to why this isn't working. If I were to send a character string containing "Hello World !", I get 3 seperate outputs, "Hello", "World" and "!".
Can anyone tell me what I'm doing wrong? Or maybe a better (read: easier) way of doing it?












