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!
You can make an instance of a socket object and call a gettimeout() method to get the default timeout value and the settimeout() method to set a specific timeout value. This is very useful in developing custom server applications.
Socket timeouts can occur when attempting to connect to a remote server, or during communication, especially long-lived ones. They can be caused by any connectivity problem on the network, such as: A network partition preventing the two machines from communicating. The remote machine crashing.
When there is a problem with the socket connection, such as the network being unavailable or there being no Internet, the socket will keep trying to connect. A socket timeout stops this connection after a specified amount of time.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With