套接字超时:它的工作原理,但为什么和怎么样,主要是select()函数? [英] socket timeout: It works, but why and how, mainly the select() function?
本文介绍了套接字超时:它的工作原理,但为什么和怎么样,主要是select()函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面是我使用的是现在code的一部分。
Here is part of the code I'm using now.
fd_set fdset;
struct timeval tv;
int flags = fcntl(sockfd, F_GETFL);
fcntl(sockfd, F_SETFL, O_NONBLOCK);
connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr));
FD_ZERO(&fdset);
FD_SET(sockfd, &fdset);
tv.tv_sec = 3;
tv.tv_usec = 0;
if (select(sockfd + 1, NULL, &fdset, NULL, &tv) == 1)
{
int so_error;
socklen_t len = sizeof so_error;
getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &so_error, &len);
if (so_error == 0) {
cout << " - CONNECTION ESTABLISHED\n";
}
} else
{
cout << " - TIMEOUT\n";
exit(-1);
}
我不认清select()函数是如何工作的,这里伪code是我真正想做的事情,
I don't clearly understand how the select() function works, here in pseudo code is what I really want to do,
bool showOnce = true;
connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr))
while(stillConnecting) /*Some kind of flag of connection status*/
{
if(showOnce)
{
showOnce = false;
cout << "Connecting";
}
}
if(connected) /*Another possible flag if it exists*/
return true;
else
return false;
反正是有实现这个伪code,做这些标志存在?
Is there anyway to implement this pseudo code, do these flags exist?
编辑:另外为什么在code以上select函数的sockfd + 1?为什么添加到它吗?
Also why is sockfd+1 in the select function in the code above? Why is one added to it?
推荐答案
阅读本手册: 2人选择
:
-
NFDs的是任何三套最高编号的文件描述符,加1。
,这就是为什么的sockfd + 1
。 -
选择()
返回一个触发请求的事件描述符的数量。只有一个描述符中给出,因此选择最多可1
返回。 - 所以,如果在3秒钟后,在给定的超时,没有任何反应,
选择()
不返回1
,所以你认为这是一个超时。一个错误的情况下1
没有被处理。
nfds is the highest-numbered file descriptor in any of the three sets, plus 1.
, that's whysockfd + 1
.select()
returns the number of descriptors which trigger a requested event. Only one descriptor is given, so select can return at most1
.- So if after 3 seconds, the given timeout, nothing happens,
select()
does not return1
, so you consider it a timeout. The case of an error-1
is not handled.
这篇关于套接字超时:它的工作原理,但为什么和怎么样,主要是select()函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文