Advertisement

Receiving issue..

Started by November 10, 2014 07:58 AM
1 comment, last by hplus0603 10 years ago
Hello! I've recently started learning network programming by simple programs. For now, I've made a simple console-based program which sends and receive some char* buffer. This is my issue :
When I send the buffer like this from the server,

//Without sleep function in between functions
SendMessageToClient(tempSock, "Test message\n"); //first message
SendMessageToClient(tempSock, "Another message!\n"); //second message
This is the output from client (i.e Second message does not get received) :
TeBvXsG.png
But when I send the buffer like this from the server,

//With sleep in between functions
SendMessageToClient(tempSock, "Test message\n"); //first message
Sleep(10);
SendMessageToClient(tempSock, "Another message!\n"); //second message
This is the output from client (i.e both messages are received):
t73oOch.png
Why there is a difference when I send the message to client from the server without sleep? (Message does not get received when sleep is not inserted between send functions.)
Full Source code:

Since you are using TCP, the first call to recv will most likely read all of the data you send. Since it is a stream and you read 500 bytes from it. So instead of reading 500 bytes read the lenght of the packet or read a chunk (500 bytes) of it and order it after that.

Advertisement
When using TCP, there is no guarantee that a single write/send on the sending side will be seen as a single read/recv on the receiving side.
Reading from a TCP stream is somewhat like reading from a file.
You need to either precede each message with a length value, and only read that many bytes on the receiving side for each message, or you need to receive into one large buffer, and parse messages out of that buffer in sequence.
Save whatever bytes are left over at the end, because they are the beginning of the next message (which may arrive in two or more parts over the network.)

This is, btw, one of the things mentioned in the FAQ for the Networking section :-)
enum Bool { True, False, FileNotFound };

This topic is closed to new replies.

Advertisement