Click here to Skip to main content
12,999,157 members (42,558 online)
Rate this:
Please Sign up or sign in to vote.
See more:
I am developing UDP client server application using VC++, I can read data using recvfrom

//this is a blocking call
	        if ((recv_len = recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, &slen)) == -1)	        {

How I can reduce this infinite waiting for a data to a fixed seconds of time ?
Posted 5-Mar-13 2:02am
Why? Better do it in a separate thread...
Arun Kumar K S 5-Mar-13 23:13pm
How I can stop that thread when no data ?

That waiting thread?

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

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 }; // will be checked for being ready to read
FD_SET(s, &fds);
// sets timeout
struct timeval tv = { 0 };
tv.tv_sec = TIMEOUT;
tv.tv_usec = 0;
int ret = select( s + 1, &fds, NULL, NULL, &tv );
if (  ret < 0 )
    // error on select()
else if ( ret == 0 )
    // timeout
    // possible function return or loop breakage
else if ( FD_ISSET( s, &fds ) ) // data to read?
    //this is a blocking call
    if ((recv_len = recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, &slen)) == -1)

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);
if ( recvfrom( ... ) < 0 )
    if ( errno == EINTR )
        // timed out
       // other error
  // no error

See manual for distinct functions.
Hope it will help you!

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[^]
Arun Kumar K S 7-Mar-13 2:47am
Thanks for your great solution

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web02 | 2.8.170622.1 | Last Updated 6 Mar 2013
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100