设置指定
输入的最大时间量
函数等待,直到它完成
接受时间结构
秒数和微秒数
指定到
wait for an input operation to
如果接收操作已完成
被堵了这么久
receiving additional data, it shall
返回部分计数或 errno
如果没有,则设置为[ EAGAIN ]或[ EWOULDBLOCK ]
data is received. The default for this
选项为零,这表明
接收操作不得超时。
此选项采用时间结构。
请注意,并非所有的实现
allow this option to be set.
// LINUX
struct timeval tv;
tv.tv_sec = timeout_in_seconds;
tv.tv_usec = 0;
setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv);
// WINDOWS
DWORD timeout = timeout_in_seconds * 1000;
setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof timeout);
// MAC OS X (identical to Linux)
struct timeval tv;
tv.tv_sec = timeout_in_seconds;
tv.tv_usec = 0;
setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv);
struct pollfd fd;
int ret;
fd.fd = mySocket; // your socket handler
fd.events = POLLIN;
ret = poll(&fd, 1, 1000); // 1 second for timeout
switch (ret) {
case -1:
// Error
break;
case 0:
// Timeout
break;
default:
recv(mySocket,buf,sizeof(buf), 0); // get your data
break;
}