Reputation: 2316
Is it possible to set timeout to accept function when using blocking winsockets? Like we can do to recv and send function via setsockopt?
Seems like it's not possible, but I want to ensure.
Upvotes: 4
Views: 10332
Reputation: 24857
It's fairly easy to arrange another thread to close the listening socket afer a timeout. Create an auto-reset event and signal it whenever accept() returns. Write a function that waits on the event with WaitForSingleObject() in a loop with the timeout interval. If the WFSO returns with anything that is not WAIT_OBJECT_0, close the listening socket and exit. Just before entering the accept() loop, create a thread to call the function.
Another possibility is to use acceptEx() and wait with a WFSO() timeout on an event passed as the hEvent of the OVERLAPPED struct. If the timeout fires, use CancelIo() to remove the queued acceptEx() completion from the network IO system.
Upvotes: 0
Reputation: 24895
Select function can be used with timeout. Though, select is most commonly used with non-blocking sockets, I haven't read anything that prevents passing a blocking socket to select. If the select function times out, then you have the behavior equivalent of accept timeout.
From MSDN
"The parameter readfds identifies the sockets that are to be checked for readability. If the socket is currently in the listen state, it will be marked as readable if an incoming connection request has been received such that an accept is guaranteed to complete without blocking. For other sockets, readability means that queued data is available for reading such that a call to recv, WSARecv, WSARecvFrom, or recvfrom is guaranteed not to block."
This should give you the behaviour you are expecting.
Upvotes: 8