To run this script, pass no arguments to talk to a server listening on port 50007 on the
local machine; pass a real machine name to talk to a server running remotely. Three
console windows come into play in this scheme—the client, a local server, and a remote
server. On Windows, the clients’ output is discarded when spawned from this script,
but it would be similar to what we’ve already seen. Here’s the client window
interaction—8 clients are spawned locally to talk to both a local and a remote server:
C:\...\PP4E\Internet\Sockets> set PYTHONPATH=C:\...\dev\Examples
C:\...\PP4E\Internet\Sockets> python testecho.py
C:\...\PP4E\Internet\Sockets> python testecho.py learning-python.com
If the spawned clients connect to a server run locally (the first run of the script on the
client), connection messages show up in the server’s window on the local machine:
C:\...\PP4E\Internet\Sockets> python echo-server.py
Server connected by ('127.0.0.1', 57721)
Server connected by ('127.0.0.1', 57722)
Server connected by ('127.0.0.1', 57723)
Server connected by ('127.0.0.1', 57724)
Server connected by ('127.0.0.1', 57725)
Server connected by ('127.0.0.1', 57726)
Server connected by ('127.0.0.1', 57727)
Server connected by ('127.0.0.1', 57728)
If the server is running remotely, the client connection messages instead appear in the
window displaying the SSH (or other) connection to the remote computer, here,
learning-python.com:
[...]$ python echo-server.py
Server connected by ('72.236.109.185', 57729)
Server connected by ('72.236.109.185', 57730)
Server connected by ('72.236.109.185', 57731)
Server connected by ('72.236.109.185', 57732)
Server connected by ('72.236.109.185', 57733)
Server connected by ('72.236.109.185', 57734)
Server connected by ('72.236.109.185', 57735)
Server connected by ('72.236.109.185', 57736)
Preview: Denied client connections
The net effect is that our echo server converses with multiple clients, whether running
locally or remotely. Keep in mind, however, that this works for our simple scripts only
because the server doesn’t take a long time to respond to each client’s requests—it can
get back to the top of the server script’s outer while loop in time to process the next
incoming client. If it could not, we would probably need to change the server to handle
each client in parallel, or some might be denied a connection.
Technically, client connections would fail after 5 clients are already waiting for the
server’s attention, as specified in the server’s listen call. To prove this to yourself, add
a time.sleep call somewhere inside the echo server’s main loop in Example 12-1 after
Socket Programming | 799