CITS3002 Computer Networks  
prev
next CITS3002 help3002 CITS3002 schedule  

Concurrent Servers Using select()

With a concurrent server, a single server handles many clients within the same process. This obviates the need for interprocess communication between multiple servers (such as file locking).

We use a new network supporting system call, select(), to inform our process which descriptors are ready for I/O. The descriptors may be open to files, devices, sockets or pipes.

select deals with sets of descriptors (implemented as an array or bitmap in C or C++) and provides functions for their manipulation.

Here we examine descriptors open for reading, timing out each 10 seconds:

#include <sys/select.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>

    bool  keep_going = true;
    ....
    while(keep_going) {
        fd_set readset;

        FD_CLR(&readset);
        FD_SET(sd, &readset);

        foreach other descriptor open for reading {
            FD_SET(desc, &readset);
        }

        struct timeval timeout;

        timeout.tv_sec  = 10;             // wait up to 10 seconds
        timeout.tv_usec =  0;

        if(select(MAXDESC, &readset, NULL, NULL, &timeout) >= 0) {
            if(FD_ISSET(sd, &readset)) {
                client = accept(sd, ...); // yet another new client
                ......
            }
            foreach other descriptor open for reading {
                if(FD_ISSET(desc, &readset)) {
                    service(desc);
                    .......
                }
            }
        }
    }

Note that this example is typical in employing only one set of file descriptors, readset. A service much more concerned about I/O speeds, particularly disk blocking, would employ another set of file descriptors, writeset, or perform asynchronous file I/O.


CITS3002 Computer Networks, Lecture 9, Client/server design, p10, 1st May 2024.