C++ – How to get the exact message from recv() in winsock programming

cwinsock

I'm developing a server-client application using Winsock in c++ and have a problem.

For getting the message from the client by the server I use the code below.

int result;
char buffer[200];

while (true)
{
    result = recv(client, buffer, 200, NULL);

    if (result > 0)
        cout << "\n\tMessage from client: \n\n\t" << message << ";";
}

I send the message "Hello" from the client to the server. However the buffer is actually this:

HelloÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ

What am I missing?

Best Answer

Since recv might not receive as many bytes as you told it, you typically use a function like this to receive specified number of bytes. Modified from here

int receiveall(int s, char *buf, int *len)
{
    int total = 0;        // how many bytes we've received
    int bytesleft = *len; // how many we have left to receive
    int n = -1;

    while(total < *len) {
        n = recv(s, buf+total, bytesleft, 0);
        if (n <= 0) { break; }
        total += n;
        bytesleft -= n;
    }

    *len = total; // return number actually received here

    return (n<=0)?-1:0; // return -1 on failure, 0 on success
} 

It's up to you to null terminate the string if you receive string which is not null terminated.

Related Topic