我在 winsock 的 recv() 循环中遇到问题。我试图在 iResult==0 时终止循环,但是,循环仅在套接字关闭时结束。它似乎卡在 iResult 等于 0 的最后一个 recv() 处。那么关于如何有效终止循环的任何想法?我的最终目标(无论 iResult == 0 与否;也许我做错了)是在读取所有发送的信息后停止循环。这是循环。
do
{
iResult = recv(socket, recvbuf, BUFLEN-1, 0);
if(iResult > 0){
// Null byte :)
// Remove that garbage >:(
recvbuf[iResult] = '\0';
printf("Recvbuf: %s\n\n\niResult: %d\n",recvbuf,iResult);
continue; // working properly
}
else if(iResult == 0)
// Connection closed properly
break;
else
{
printf("ERROR! %ld",WSAGetLastError());
break;
}
} while(iResult > 0);
就像我说的,我正在接收所有数据,只是无法退出循环。下一步是将数据写回服务器,但它一直卡在这里直到 ping 超时。 Socket为SOCK_STREAM,BUFLEN定义为0x200
谢谢
最佳答案
默认情况下,recv
blocks if there's no data to receive 不是返回 0 :
If no incoming data is available at the socket, the recv call blocks and waits for data to arrive according to the blocking rules defined for WSARecv with the MSG_PARTIAL flag not set unless the socket is nonblocking. In this case, a value of SOCKET_ERROR is returned with the error code set to WSAEWOULDBLOCK. The select, WSAAsyncSelect, or WSAEventSelect functions can be used to determine when more data arrives.
您可以使用 ioctlsocket将套接字置于非阻塞模式:
u_long iMode = 1;
ioctlsocket(socket, FIONBIO, &iMode);
编辑:这是我在较早版本中提出的 setsockopt 建议,然后删除(参见评论):
You can use the setsockopt function with the
SO_RCVTIMEO
option to set the socket to timeout onrecv
if no data is available.
关于c++ - 使用 Winsock 读取所有信息时结束 "recv()"循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3340336/