Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 << "
Message from client: 

" << message << ";";
}

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

Helloììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììììì

What am I missing?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
240 views
Welcome To Ask or Share your Answers For Others

1 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...