[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1
[server window (SSH or Telnet)]
[...]$ uname -p -o
i686 GNU/Linux
[...]$ python fork-server.py
Server connected by ('72.236.109.185', 58395) at Sat Apr 24 06:46:45 2010
Server connected by ('72.236.109.185', 58396) at Sat Apr 24 06:46:49 2010
Server connected by ('72.236.109.185', 58397) at Sat Apr 24 06:46:51 2010

[client window 1]
C:\...\PP4E\Internet\Sockets> python echo-client.py learning-python.com
Client received: b"Echo=>b'Hello network world' at Sat Apr 24 06:46:50 2010"

[client window 2]
C:\...\PP4E\Internet\Sockets> python echo-client.py learning-python.com Bruce
Client received: b"Echo=>b'Bruce' at Sat Apr 24 06:46:54 2010"

[client window 3]
C:\...\Sockets> python echo-client.py learning-python.com The Meaning of Life
Client received: b"Echo=>b'The' at Sat Apr 24 06:46:56 2010"
Client received: b"Echo=>b'Meaning' at Sat Apr 24 06:46:56 2010"
Client received: b"Echo=>b'of' at Sat Apr 24 06:46:56 2010"
Client received: b"Echo=>b'Life' at Sat Apr 24 06:46:57 2010"

Again, all times here are on the server machine. This may be a little confusing because
four windows are involved. In plain English, the test proceeds as follows:



  1. The server starts running remotely.

  2. All three clients are started and connect to the server a few seconds apart.

  3. On the server, the client requests trigger three forked child processes, which all
    immediately go to sleep for five seconds (to simulate being busy doing something
    useful).

  4. Each client waits until the server replies, which happens five seconds after their
    initial requests.


In other words, clients are serviced at the same time by forked processes, while the main
parent process continues listening for new client requests. If clients were not handled
in parallel like this, no client could connect until the currently connected client’s five-
second delay expired.


In a more realistic application, that delay could be fatal if many clients were trying to
connect at once—the server would be stuck in the action we’re simulating with
time.sleep, and not get back to the main loop to accept new client requests. With
process forks per request, clients can be serviced in parallel.


Notice that we’re using the same client script here (echo-client.py, from Exam-
ple 12-2), just a different server; clients simply send and receive data to a machine and
port and don’t care how their requests are handled on the server. The result displayed
shows a byte string within a byte string, because the client sends one to the server and
the server sends one back; because the server uses string formatting and manual


Handling Multiple Clients | 805
Free download pdf