简体   繁体   中英

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);
    }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM