[英]recv() return -1 on peer disconnect for non blocking tcp ip socket
我正在使用 tcp/ip 套接字,并且我已经阅读了有关recv
function 的信息。 因此,每当根据文档断开对等点时,recv 返回 0,但在 windows 上,它不是返回零,而是返回 -1,并且errono
中的值是0
,我无法理解它为什么这样做。 相同的代码在 linux 中运行完美。
// some headers i used
#ifdef _WIN32
/* See http://stackoverflow.com/questions/12765743/getaddrinfo-on-win32 */
# ifndef _WIN32_WINNT
# define _WIN32_WINNT 0x0501 /* Windows XP. */
# endif
# include <Ws2tcpip.h>
# include <winsock2.h>
# ifdef _MSC_VER
# pragma comment(lib, "Ws2_32.lib")
# endif
# define SHUT_RDWR SD_BOTH
#else
/* Assume that any non-Windows platform uses POSIX-style sockets instead. */
# include <arpa/inet.h>
# include <fcntl.h>
# include <netinet/in.h>
# include <netinet/tcp.h>
# include <sys/socket.h>
# include <unistd.h>
# define NO_ERROR 0
# define INVALID_SOCKET -1
# define SOCKET_ERROR -1
#endif
// MSG_DONTWAIT is not available on some platforms, if it doesn't exist define it as 0
#if !defined(MSG_DONTWAIT)
# define MSG_DONTWAIT 0
#endif
//
std::vector<std::string> Peer::read(const int length)
{
static std::vector<char> tempRecvBuf(2 * 1000000);
tempRecvBuf.clear();
int recv = ::recv(m_socket.resource(), &tempRecvBuf[0], length, MSG_DONTWAIT);
if (recv == SOCKET_ERROR ) {
if (errno == WSAECONNRESET) {
return {};
}
else {
return {};
}
if (recv == 0) {
// Connection is no longer valid, remote has been disconnected
m_connected = false;
this->m_master->events()->onPeerDisconnect()->trigger(this);
this->m_master->peers()->remove(this);
return {};
}
根据Microsoft Windows Sockets 文档的此页面, function recv
将在正常关机和SOCKET_ERROR
(包括)正常关机时返回0
(包括) -1
错误。 如文档中所述,您必须调用WSAGetLastError
来获取错误代码。 它不存储在errno
中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.