WinSock的recv返回值处理

来源:互联网 发布:ios软件源 编辑:程序博客网 时间:2024/06/11 09:21

今天在调试程序的时候发现,客户端调用closesocket时,服务器应该会返回SOCKET_ERROR,实际上Debug版本是这样,但Release版本并不是。相同的代码Debug返回了-1,Release返回了0。

通过看msdn的原文可以发现:

If no error occurs, recv returns the number of bytes received and the buffer pointed to by the buf parameter will contain this data received. If the connection has been gracefully closed, the return value is zero.Otherwise, a value of SOCKET_ERROR is returned

意思是:如果没有错误,将返回接收到的字节数。如果优雅的关闭了套接字,会返回0。否则返回SOCKET_ERROR,也就是-1。

所以在处理断线的时候判断返回值小于等于0即可。(而不是有些人写的判断等于SOCKET_ERROR)