You need to redesign your protocol. The main issue here is that you don't give the size of the message that you're sending before the message itself, and therefore you don't know how much to read from the input stream for each message.
Here's an example for a really simple protocol. Each message consists of two fields:
- Size (unsigned int).
- The message itself.
Then, for each message you read twice. First, you read the message size sizeof(unsigned int)
, then read the message itself (you now know its size).
This also removes the necessity for the null separator between messages, which can possibly occur inside your message if you don't escape it correctly, and can cause serious problems.