It is because of stream nature of socket writes and reads. You must implement your own message distinguish technique.
Some variants are:
- Worser: implement your own message end symbol.
- Better: before the message send size of that message (measured in bytes). And at first read the size, then read number of bytes given by size.
And use C++11, it's 2015 year today, don't do the old C style.
For example (error checking omitted for simplicity of the example):
Server side:
// choose this type once and never change it after first release!
using message_size_t = uint64_t;
void write_message(int sockfd, const std::string & message)
{
message_size_t message_size{ static_cast<message_size_t>(message.size()) };
// check error here:
write(sockfd, &message_size, sizeof(message_size));
// and here:
write(sockfd, message.data(), message_size);
}
// use:
write_message(sockFd, message);
write_message(sockFd, message2);
Client side:
void read_bytes_internal(int sockfd, void * where, size_t size)
{
auto remaining = size;
while (remaining > 0) {
// check error here
auto just_read = recv(sockfd, where, remaining);
remaining -= just_read;
}
}
std::string read_message(int sockfd)
{
message_size_t message_size{ 0 };
read_bytes_internal(sockfd, &message_size, sizeof(message_size));
std::string result{ message_size, 0 };
read_bytes_internal(sockfd, &result[0], message_size);
return result;
}
// use:
cout << "Msg1 " << read_message(listenFd) << endl;
cout << "Msg2 " << read_message(listenFd) << endl;
(Code may contain some small errors, I wrote it right here in stackoverflow answer window and didn't syntax-check it in IDE.)