首页 > 解决方案 > 套接字 - 使用 select 超时

问题描述

我正在尝试学习套接字。到目前为止,我成功打开了一个套接字(作为服务器),连接并发送和接收了一些数据。
现在我试图限制等待时间accept()
我找到了一些代码示例,但我现在没有任何成功:

      //socket, bind...
      listen(this->sockfd, 1);

      int iResult;
      struct timeval tv;
      fd_set rfds;
      FD_ZERO(&rfds);
      FD_SET(0, &rfds);

      tv.tv_sec = 5;
      iResult = select(0, &rfds, (fd_set *) 0, (fd_set *) 0, &tv);
      if(iResult > 0)
      {
          std::cout<< "connected"<<endl;
      } else {
          std::cout<< "time out!" << endl;
      } 

我总是得到“超时!”。
你能把手指放在哪里错了吗?谢谢

标签: c++socketsselect

解决方案


改变

FD_SET(0, &rfds);
// ...
iResult = select(0, &rfds, (fd_set *) 0, (fd_set *) 0, &tv);

FD_SET(this->sockfd, &rfds);
// ...
iResult = select(this->sockfd + 1, &rfds, nullptr, nullptr, &tv);

推荐阅读