首页 > 解决方案 > How to make recv call non blocking and make it to wait only 5 second

问题描述

How to make recv call non blocking and make it to wait only 5 second!

// Receive until the peer closes the connection
do {

    iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
    if ( iResult > 0 )
        printf("Bytes received: %d\n", iResult);
    else if ( iResult == 0 )
        printf("Connection closed\n");
    else
        printf("recv failed with error: %d\n", WSAGetLastError());

} while( iResult > 0 );

标签: timeoutblockingwinsock2recv

解决方案


fd_set readfds;
struct timeval count;
FD_ZERO(&readfds);
FD_SET(sockfd, &readfds);
select(0, &readfds, 0, 0, &count);
if (FD_ISSET(sockfd, &readfds))
{   
     if ((bytes=recv(sockfd, buffer2, 200, 0)) == -1) {
          return 0;
     }
}

推荐阅读