将超时设置为接收功能 [英] Setting timeout to recv function

查看:86
本文介绍了将超时设置为接收功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 recv 函数从套接字读取.没有可用的数据读取时,我有问题.我的程序刚刚停止.我发现可以使用 select 函数设置超时时间.但是看起来超时会影响select函数本身,而select之后的 recv 仍然会不连续地等待.

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 select function. But looks that timeout affects select function itself and recv that goes after select still waits uncontinuously.

fd_set set;
struct timeval timeout;
FD_ZERO(&set); /* clear the set */
FD_SET(s, &set); /* add our file descriptor to the set */
timeout.tv_sec = SOCKET_READ_TIMEOUT_SEC;
timeout.tv_usec = 0;
int rv = select(s, &set, NULL, NULL, &timeout);
if((recv_size = recv(s , rx_tmp , bufSize ,0)) == SOCKET_ERROR)
      {
      ...
      }

如何在经过一定的时间限制后要求 recv 函数返回?

How to ask recv function return after some timout?

推荐答案

您应检查 select 的返回值.如果超时到期, select 将返回 0 ,因此只有在返回 select 的情况下,才应检查错误并调用 recv .正值:

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:

成功后,select()和pselect()返回三个返回的描述符集中包含的文件描述符的数量(即readfds,writefds,exceptfds中设置的总位数),如果满足,则为零超时在任何有趣的事情发生之前就结束了.

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...
    }
}

这篇关于将超时设置为接收功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆