简体   繁体   English

c ++ winsock recv在接收0数据时终止线程而不是返回错误代码

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

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). 所有文档都表明,尝试recv()太多次只会导致它返回0或-1(取决于具体情况)。 Instead it's killing the thread with some sort of IOError (at the line with the recv call). 相反,它使用某种IOError(在recv调用的行)杀死线程。 What am I missing? 我错过了什么?

Edit: sad is just some stringstream. 编辑: sad只是一些字符串流。 I promise it has nothing to do with the problem :D 我保证这与问题无关:D

Another Edit: included errno.h and checked for errno codes, to no avail. 另一个编辑:包括errno.h并检查errno代码,无济于事。

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

Perhaps you should also check errno , since there might be a permature end to the communication channel. 也许您还应该检查errno ,因为通信通道可能有一个过早的结束。

#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';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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