c++ - 使用 Winsock 读取所有信息时结束 "recv()"循环

标签 c++ windows winapi winsock recv

我在 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 on recv if no data is available.

关于c++ - 使用 Winsock 读取所有信息时结束 "recv()"循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3340336/

相关文章:

c++ - 在 Boost.Spirit 中,为什么 vector 需要融合包装器(包装在结构中),而不是变体?

c++ - 每次需要其中一个类的实例时,拥有一组类的额外拷贝或从文件中读取是否会占用更多内存?

windows - 运行进程 Win32Api 的管道输出(stdout)

python - 如何使用 WMI/COM 连接到链路本地 IPv6?

c++ - 新建桌面收不到键盘事件

c++ - 诺依曼的随机生成器

c++ - 如何克服 double 不准确?

windows - 使用已登录用户的用户名在 Windows 登录上获取邮件

c - 从 OpenGL C 程序制作视频

windows - 无法创建目录 '/home/username/.ssh'