Setting timeout to recv function

前端 未结 3 1598
生来不讨喜
生来不讨喜 2020-12-28 19:53

I read from socket using recv function. I have problem when no data available for reading. My programm just stops. I found that I can set timeout using se

3条回答
  •  被撕碎了的回忆
    2020-12-28 20:24

    You should check return value of select. select will return 0 in case timeout expired, so you should check for error and call recv only if select returned positive value:

    On success, select() and pselect() return the number of file descriptors contained in the three returned descriptor sets (that is, the total number of bits that are set in readfds, writefds, exceptfds) which may be zero if the timeout expires before anything interesting happens.

    int rv = select(s + 1, &set, NULL, NULL, &timeout);
    if (rv == SOCKET_ERROR)
    {
        // select error...
    }
    else if (rv == 0)
    {
        // timeout, socket does not have anything to read
    }
    else
    {
        // socket has something to read
        recv_size = recv(s, rx_tmp, bufSize, 0);
        if (recv_size == SOCKET_ERROR)
        {
            // read failed...
        }
        else if (recv_size == 0)
        {
            // peer disconnected...
        }
        else
        {
            // read successful...
        }
    }
    

提交回复
热议问题