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

(yzsuai) #1

data = self.request.recv(1024) # read, write a client socket
if not data: break
reply = 'Echo=>%s at %s' % (data, now())
self.request.send(reply.encode())
self.request.close()


make a threaded server, listen/handle clients forever


myaddr = (myHost, myPort)
server = socketserver.ThreadingTCPServer(myaddr, MyClientHandler)
server.serve_forever()


This server works the same as the threading server we wrote by hand in the previous
section, but instead focuses on service implementation (the customized handle
method), not on threading details. It is run the same way, too—here it is processing
three clients started by hand, plus eight spawned by the testecho script shown we wrote
in Example 12-3:


[window 1: server, serverHost='localhost' in echo-client.py]
C:\...\PP4E\Internet\Sockets> python class-server.py
('127.0.0.1', 59036) Sun Apr 25 13:50:23 2010
('127.0.0.1', 59037) Sun Apr 25 13:50:25 2010
('127.0.0.1', 59038) Sun Apr 25 13:50:26 2010
('127.0.0.1', 59039) Sun Apr 25 13:51:05 2010
('127.0.0.1', 59040) Sun Apr 25 13:51:05 2010
('127.0.0.1', 59041) Sun Apr 25 13:51:06 2010
('127.0.0.1', 59042) Sun Apr 25 13:51:06 2010
('127.0.0.1', 59043) Sun Apr 25 13:51:06 2010
('127.0.0.1', 59044) Sun Apr 25 13:51:06 2010
('127.0.0.1', 59045) Sun Apr 25 13:51:06 2010
('127.0.0.1', 59046) Sun Apr 25 13:51:06 2010

[windows 2-4: client, same machine]
C:\...\PP4E\Internet\Sockets> python echo-client.py
Client received: b"Echo=>b'Hello network world' at Sun Apr 25 13:50:28 2010"

C:\...\PP4E\Internet\Sockets> python echo-client.py localhost Arthur
Client received: b"Echo=>b'Arthur' at Sun Apr 25 13:50:30 2010"

C:\...\PP4E\Internet\Sockets> python echo-client.py localhost Brave Sir Robin
Client received: b"Echo=>b'Brave' at Sun Apr 25 13:50:31 2010"
Client received: b"Echo=>b'Sir' at Sun Apr 25 13:50:31 2010"
Client received: b"Echo=>b'Robin' at Sun Apr 25 13:50:31 2010"

C:\...\PP4E\Internet\Sockets> python testecho.py

To build a forking server instead, just use the class name ForkingTCPServer when cre-
ating the server object. The socketserver module has more power than shown by this
example; it also supports nonparallel (a.k.a. serial or synchronous) servers, UDP and
Unix domain sockets, and Ctrl-C server interrupts on Windows. See Python’s library
manual for more details.


For more advanced server needs, Python also comes with standard library tools that
use those shown here, and allow you to implement in just a few lines of Python code a


Handling Multiple Clients | 819
Free download pdf