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;
//默认为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;
}