Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
248 views
in Technique[技术] by (71.8m points)

c++ - How to get the exact message from recv() in winsock programming?

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...