CSCI 485 lab 2: non-blocking IO and receives

As discussed in Thursday's lecture, this lab will focus on using non-blocking keyboard input and non-blocking receives to develop single-threaded clients and servers.

The first goal is to take your code from last week and make the receives non-blocking (see the first discussion session and examples below).

The second goal is to make the user input non-blocking (see the second discussion section and examples below).

Note that judicious use of the usleep(nMicroseconds) function will take a lot of burden off the cpu in your 'waiting for something to do' loops!

Non-blocking receives

The change to make a receive non-blocking is simply a matter of setting a flag on the socket. The complete example is in a revamped version of server.C, with the key changes being here:

// the receives are blocking or not based on the blocking flag
void processMessages(int sockfd, bool blocking)
{
    // set the socket to be blocking or not
    int flags = fcntl(sockfd, F_GETFL);
    if (!blocking) flags |= O_NONBLOCK;
    fcntl(sockfd, F_SETFL, flags);

    ... then inside the do while loop ...

       if (numbytes <= 0) {
           cout << "No messages currently waiting\n";

Non-blocking keyboard input

This is a little more involved given the platform and language constraints we're working with, but we can use termios to our advantage in detecting if a key has been pressed, and capturing it from the input buffer if so.

In files keyPress.h and keyPress.C I provide two routines:

An example of using these in non-blocking receives is given in keyTest.C.

Just for completeness, a Makefile and printFiles script are included.