Don't use the threads unless you really have to.
You have a several alternatives.
I suggest to use select() or poll() functions.
select() also appears in windows sockets API and has a syntax similar to BSD API.
So this one could be the most universal in simple cases.
struct fd_set fds = { 0 }; FD_ZERO(&fds);
FD_SET(s, &fds);
struct timeval tv = { 0 };
tv.tv_sec = TIMEOUT;
tv.tv_usec = 0;
int ret = select( s + 1, &fds, NULL, NULL, &tv );
if ( ret < 0 )
{
}
else if ( ret == 0 )
{
}
else if ( FD_ISSET( s, &fds ) ) {
if ((recv_len = recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, &slen)) == -1)
{
die("recvfrom()");
}
}
But maybe, instead of writing a recvfrom-like function with time-out you may want to redesign the application. Use non-blocking API or use select()/poll() or smth else in the main loop
(do research, there are multiple choices).
On UNIX/Linux you can use also SIGALRM eg.:
signal(SIGALRM, sig_alrm);
alarm(TIMEOUT);
if ( recvfrom( ... ) < 0 )
if ( errno == EINTR )
else
else
alarm(0);
See manual for distinct functions.
Hope it will help you!
Regards!
P.S.
I overlooked that you are using VC++. select() based solution works fine.
You would rather don't find alarm() and sigaction() helpful. In Windows there are WaitForMultipleObjects or IO Completion Ports for creating high performance servers.
It is very interesting issue. I encourage you to explore this topic if you want to write a professional server software.
Quick search and I've found, for instance, this article:
IP Multicasting - Using I/O completion ports with UDP[
^]