Running the select server
Let’s run this script locally to see how it does its stuff (the client and server can also be
run on different machines, as in prior socket examples). First, we’ll assume we’ve al-
ready started this server script on the local machine in one window, and run a few
clients to talk to it. The following listing gives the interaction in two such client console
windows running on Windows. The first client simply runs the echo-client script twice
to contact the server, and the second also kicks off the testecho script to spawn eight
echo-client programs running in parallel.
As before, the server simply echoes back whatever text that client sends, though without
a sleep pause here (more on this in a moment). Notice how the second client window
really runs a script called echo-client-50008 so as to connect to the second port socket
in the server; it’s the same as echo-client, with a different hardcoded port number;
alas, the original script wasn’t designed to input a port number:
[client window 1]
C:\...\PP4E\Internet\Sockets> python echo-client.py
Client received: b"Echo=>b'Hello network world' at Sun Apr 25 14:51:21 2010"
C:\...\PP4E\Internet\Sockets> python echo-client.py
Client received: b"Echo=>b'Hello network world' at Sun Apr 25 14:51:27 2010"
[client window 2]
C:\...\PP4E\Internet\Sockets> python echo-client-5008.py localhost Sir Galahad
Client received: b"Echo=>b'Sir' at Sun Apr 25 14:51:22 2010"
Client received: b"Echo=>b'Galahad' at Sun Apr 25 14:51:22 2010"
C:\...\PP4E\Internet\Sockets> python testecho.py
The next listing is the sort of output that show up in the window where the server has
been started. The first three connections come from echo-client runs; the rest is the
result of the eight programs spawned by testecho in the second client window. We can
run this server on Windows, too, because select is available on this platform. Correlate
this output with the server’s code to see how it runs.
Notice that for testecho, new client connections and client inputs are multiplexed to-
gether. If you study the output closely, you’ll see that they overlap in time, because all
activity is dispatched by the single event loop in the server. In fact, the trace output on
the server will probably look a bit different nearly every time it runs. Clients and new
connections are interleaved almost at random due to timing differences on the host
machines. This happens in the earlier forking and treading servers, too, but the oper-
ating system automatically switches between the execution paths of the dispatcher loop
and client transactions.
Also note that the server gets an empty string when the client has closed its socket. We
take care to close and delete these sockets at the server right away, or else they would
be needlessly reselected again and again, each time through the main loop:
[server window]
C:\...\PP4E\Internet\Sockets> python select-server.py
Handling Multiple Clients | 823