c++ - 套接字 - 使用 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;
}
我总是得到“超时!”。
你能把手指放在哪里错了吗?谢谢
解决方案
改变
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);
推荐阅读
- reactjs - 如何使用参数弹出到上一个屏幕?
- sql - DateDiff 噩梦
- python - Kivy 如何赋予所有对象相同的基本功能
- java - 如何在java中对日期进行排序?
- tensorflow - ValueError:没有为任何变量 tensorflow 2.0 提供梯度
- c# - 无法在 Internet Explorer Web 驱动程序中找到更新面板的元素
- python - 两个 pyspark Dataframe 列之间的高效匹配
- java - 如何将对象数组转换为任意内容类型 T (Object[] -> T[])
- c# - How to get migration of Database in c# project
- java - Firebase Messaging Notifications not coming through even though database correctly referenced