Min Kim
Min Kim

Reputation: 113

recv() always return 1

I have a client-server that needs stay connected. So I'm really confused about when to stop receiving data. The recv() always return 1. And while() can't stop!

    int nbytes = 0;
    char buf_to_parse[4096] = { '\0' };
    char saveAll[20480] = { '\0' }; 

    while ((nbytes = recv(wParam, buf_to_parse , 4096 , 0) != 0)) //nbytes is always 1
    {
        sprintf_s(saveAll, "%s%s", saveAll, buf_to_parse);
    }

Upvotes: 0

Views: 1288

Answers (1)

Sami Kuhmonen
Sami Kuhmonen

Reputation: 31153

This is because you are doing a comparison and that is cast into an integer. When you say

nbytes = recv(wParam, buf_to_parse , 4096 , 0) != 0

because of operator presedence it means

nbytes = (recv(wParam, buf_to_parse , 4096 , 0) != 0)

which just tests if the return value of recv() is not zero and puts false or true (0 or 1 by convention) into nbytes. What you want is

(nbytes = recv(wParam, buf_to_parse , 4096 , 0)) > 0

This will set the number of bytes into nbytes and then compare the value. You must also take into account negative values in error conditions, not only the zero which is only given on proper disconnection.

The code you had would have worked for the while if the closing is done properly, but nbytes would've been wrong anyway.

Upvotes: 4

Related Questions