How can I add heartbeat functionality to asynchronous sockets client.

Hello,

I have the sample code from chapter 16.2 of Sockets book by Richard Stevens which is an asynchronous client that reads/writes into sockets/stdin/stdout. The simplified version is below. Now I need to enhance this code so it will send
a heartbeat to a server if there was not any communication with the server for 60 seconds. Currently this code hangs indefinitely at select() untill the data appear at the socket or stdin.

I'll appriciate any suggestions how I can add the heartbeat functionality. I am running Ubuntu.

Thank you!



for ( ; ; )
{
select(maxfdp1, &rset, &wset, NULL, NULL);

// read from stdin.
if ( FD_ISSET(STDIN_FILENO, &rset) )
n = read(STDIN_FILENO, toiptr, &to[MAXLINE] - toiptr));

// read from socket.
if ( FD_ISSET(sockfd, &rset) )
n = read(sockfd, friptr, &fr[MAXLINE] - friptr);

// write to stdout.
if (FD_ISSET(STDOUT_FILENO, &wset) )
nwritten = write(STDOUT_FILENO, froptr, n);

// write to socket.
if (FD_ISSET(sockfd, &wset) )
nwritten = write(sockfd, tooptr, n);

} // for ( ; ; )
You can use select to do the timing. Set the sleep interval, and if it times out, write a message to the socket.
Right, the struct timeval - thank you!
I have a problem with timing in select() now. I modified my app:

timeval timeout;
timeout.tv_sec = 5;
timeout.tv_usec = 0;

for ( ; ; )
{
int ret = select(maxfdp1, &rset, &wset, NULL, &timeout);
if( ret == 0) // timed out
{
// HEARTBEAT FUNCTIONALITY HERE;
}

// read from stdin.
if ( FD_ISSET(STDIN_FILENO, &rset) )
n = read(STDIN_FILENO, toiptr, &to[MAXLINE] - toiptr));

// read from socket.
if ( FD_ISSET(sockfd, &rset) )
n = read(sockfd, friptr, &fr[MAXLINE] - friptr);

// write to stdout.
if (FD_ISSET(STDOUT_FILENO, &wset) )
nwritten = write(STDOUT_FILENO, froptr, n);

// write to socket.
if (FD_ISSET(sockfd, &wset) )
nwritten = write(sockfd, tooptr, n);

} // for ( ; ; )


It waits 5 seconds but only on the first iteration of the loop, on subsequent iterations select() does not wait at all, it just goes right through. I expected it to wait every time.

Could someone help me with this so select() times out every time?

TIA!






Last edited on
Move timeval and its initialisation into the loop, before select() of course.
Thank you again!
Topic archived. No new replies allowed.