socket timeout: It works, but why and how, mainly the select() function?
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_ERRO开发者_运维问答R, &so_error, &len);
if (so_error == 0) {
cout << " - CONNECTION ESTABLISHED\n";
}
} else
{
cout << " - TIMEOUT\n";
exit(-1);
}
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;
Is there anyway to implement this pseudo code, do these flags exist?
EDIT: Also why is sockfd+1 in the select function in the code above? Why is one added to it?
Read the manual: man 2 select
:
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.
精彩评论