如何检测我是否有东西要从套接字读取?(c++)

Dar*_*ius 3 c++ sockets

我试图在一定时间内收到客户的答复。我怎么能那样做呢?我的意思是我有那个代码

 unsigned secondsElapsed = 0;
    while(secondsElapsed <= TIMER){
        char tBuffer[32];

    if (recv(clientSocket, tBuffer, sizeof(tBuffer), MSG_PEEK | MSG_DONTWAIT) == 0){
            myPlayer->dcPlayer();
            \\ More stuff to do if player is dissconected
    \\ But if is not dc, and is typing, how can i check my socket to see
    \\ if i have an answer there to read, else i`ll increment 
    \\ secondsElapsed until is equal to TIMER or until i get an answer    
    \\ from my client.

    usleep(1000000);
    secondsElapsed++;
    }
Run Code Online (Sandbox Code Playgroud)

所以,问题是:我如何检查我的客户是否给我发送了答案?如果我尝试阅读,那么我的程序将被卡住,并且我将无法增加已用秒数。

Ser*_*eyA 5

您在这里有多种选择。首先,您可以使用非阻塞套接字(通常不是很好的解决方案)。更好的选择是使用操作系统提供的轮询/异步通知机制 - 例如,在 *Nix 上用户可以选择selectpollepoll,而 Windows 有自己的异步事件通知 API,例如 I/O 完成端口,如下所述:https://msdn.microsoft.com/en-gb/library/windows/desktop/aa365198(v=vs.85).aspx