You said you have a TCP protocol, what you have is not a protocol that’s just a TCP connection.
In order to implement a protocol you need to send some more information, the recv() part should (must) know what is going to receive.
You need to send either, ahead the length of the buffer or a terminating char, at the end of the buffer, which should not be part of the rest of the sent message. Characters like Line-Feed (10), Carriage-Return (13) and Form-Feed (12) are good candidates.
If you decide to use a terminating character, then, you should read (recv) one char at a time, verifying if that is the terminating indicator. Terminating characters are only useful when sending strings which represent literal words, is not indicated to be used for sending files or images or binary strings.
I've modified your routines implementing the length of the buffer indicator method:
bool Socket::Sender(char* msg){
// Send a string with the length (int) of it ahead
int len = strlen(msg);
int hLen = htonl(len); // put it in network byte order
if (send(sockfd, (char *) &hLen, sizeof(int), 0) == sizeof(int) &&
send(sockfd, msg, len, 0) == len)
{
return true;
}
Close();
return false;
}
int Socket::Receive(char* msg, int maxlen){
int recvResult;
int len;
int offset;
// receive a string with the length (int) of it first
if (recv(sockfd, (char *) &len, sizeof(int), 0) == sizeof(int))
{
len=ntohl(len); // put in host byte order
// Check there is enough space
if (len > maxlen)
{
// the receive chars is bigger than maxlen,
// either receive as many as maxlen or return error
len=maxlen;
// Close();
// return -1;
}
offset=0;
// loop until len chars are received, no more no less
while (offset < len)
{
recvResult = recv(sockfd, (char *) &msg[offset], len-offset, 0);
if (recvResult <= 0)
{
Close();
return -1;
}
offset +=recvResult;
}
// Succeeded, return len
return len;
}
Close();
return -1;
}