网络中超时接收的函数之一 select

int ReadTimeOut(int nSocket, unsigned int nWaitSeconds) {
//默认为0,当wait_seconds==0时,不检测直接返回0
int nRet = 0;
//需要检测超时
if (nWaitSeconds > 0) {
fd_set stReadSocketSet;  //读套接字结构体
struct timeval stTimeOut;  //超时结构体
FD_ZERO(&stReadSocketSet);


//将要监听的套接字放到读套接字结构体中
FD_SET(nSocket, &stReadSocketSet);


stTimeOut.tv_sec = nWaitSeconds;
stTimeOut.tv_usec = 0;
do {
nRet = select(nSocket + 1, &stReadSocketSet, NULL, NULL,
&stTimeOut);
//select会阻塞直到检测到事件或则超时,如果超时,select会返回0,
//如果检测到事件会返回1,如果异常会返回-1,如果是由于信号中断引起的异常errno==EINTR
//如果是有信号引起的异常则继续阻塞select,直到检测到事件或则超时
} while (nRet < 0 && errno == EINTR);
//select超时退出
if (nRet == 0) {
cout << "读超时" << endl;
nRet = -1;
errno = ETIMEDOUT;
}
//select检测到可读事件
else if (nRet == 1) {
//cout<<"可读"<<endl;
nRet = 0;
}
}
return nRet;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值