Network Programming with Perl By Lincoln D. Stein Slots : 1
Table of Contents
Part 3: Developing TCP Client/Server Systems
Content
The forking and threading techniques discussed in the last two chapters allow a program to handle multiple concurrent connections. The last general technique that we cover is I/O multiplexing. Multiplexing doesn't take advantage of any operating system tricks to achieve the illusion of concurrency. Instead, multiplexed applications handle all connections in one main loop. For example, a server that is currently servicing ten clients reads from each connected socket in turn , handles the request, and then services the next client.
The big problem with interleaving I/O in this way is the risk of blocking. If you try to read from a socket that doesn't have data ready, the read() and sysread () calls will block until new data is received. When you're serving multiple connections, this is unacceptable because it causes all the connections to stall until the connection you're waiting on becomes ready. Another potential problem is that if the client on the other end isn't ready to read, then calls to syswrite() or print() will also block. The performance of the server is held hostage to the performance of the slowest client.
The key to multiplexing is a built-in function called select() and its object-oriented equivalent, the IO::Select module. With select() you can check whether an I/O operation on a filehandle will block before performing the operation. This chapter discusses how to use these facilities.