How to accept socket with timeout
Solution 1
The first parameter of the select
call should be equal to the the highest number file descriptor in your fd_set set plus 1 (see here). Try changing the first argument to s+1
; you will need to add some logic when your have more than one socket in your set.
Solution 2
The first argument of select() is an int that is at least 1 greater than the highest value of the file descriptors in any of the bitsets. In this case
iResult = select(s + 1, &rfds, (fd_set *) 0, (fd_set *) 0, &tv);
should work.
Solution 3
select()
returns >0 if a socket is signaled, 0 on timeout, and -1 on error. What value is select()
actually returning to you? You are only checking for >0 and <=0, which means you are not differentiating between -1 and 0. If it is returning 0 then no client is connecting to your socket, but if it is returning -1 then your socket is likely not valid to begin with.
Boris
Updated on September 25, 2020Comments
-
Boris over 3 years
Is there is a timeout crossplatform soulution to accept client using
accept
function without setting socket to non-blocking?I know that i should use
select
function to it, but what i'm doing wrong?SOCKET NativesAcceptClient(SOCKET s, int timeout) { int iResult; struct timeval tv; fd_set rfds; FD_ZERO(&rfds); FD_SET(s, &rfds); tv.tv_sec = (long)timeout; tv.tv_usec = 0; iResult = select(s, &rfds, (fd_set *) 0, (fd_set *) 0, &tv); if(iResult > 0) { return accept(s, NULL, NULL); } else { //always here, even if i connect from another application } return 0; }
How to fix that? Thanks!