Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ winsock recv terminates thread instead of returning error code when receiving 0 data

Tags:

c++

recv

winsock

A valid socket connection is already established to a server. There's a simple loop designed to continue receiving data until the server stops sending any more. All the documentation indicates that trying recv() too many times should just cause it to return 0 or -1 (depending on the situation). Instead it's killing the thread with some sort of IOError (at the line with the recv call). What am I missing?

Edit: sad is just some stringstream. I promise it has nothing to do with the problem :D

Another Edit: included errno.h and checked for errno codes, to no avail.

do {            
    memset(buffer,0,sizeof(buffer));
    bytes = recv(s,buffer,sizeof(buffer)-40,0);
    sad << buffer;
    Sleep(1);
} while (bytes>0);
like image 718
TheToolBox Avatar asked Nov 24 '25 01:11

TheToolBox


1 Answers

Perhaps you should also check errno, since there might be a permature end to the communication channel.

#include <errno.h>
#include <string.h>

do {            
    memset(buffer,0,sizeof(buffer));
    bytes = recv(s,buffer,sizeof(buffer)-40,0);
    if (errno)
       break;
    sad << buffer;
    Sleep(1);
} while (bytes>0);

if (errno)
   std::cerr << "Premature end of connection: " << strerror(errno) << '\n';
like image 53
sehe Avatar answered Nov 25 '25 17:11

sehe