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

(yzsuai) #1
while True: # wait for next connection,
connection, address = sockobj.accept() # pass to process for service
print('Server connected by', address, end=' ')
print('at', now())
Process(target=handleClient, args=(connection,)).start()

if __name__ == '__main__':
print('Parent:', os.getpid())
sockobj = socket(AF_INET, SOCK_STREAM) # make a TCP socket object
sockobj.bind((myHost, myPort)) # bind it to server port number
sockobj.listen(5) # allow 5 pending connects
dispatcher()

This server variant is noticeably simpler too. Like the forking server it’s derived from,
this server works fine under Cygwin Python on Windows running as localhost, and
would probably work on other Unix-like platforms as well, because multiprocessing
forks a process on such systems, and file and socket descriptors are inherited by child
processes as usual. Hence, the child process uses the same connected socket as the
parent. Here’s the scene in a Cygwin server window and two Windows client windows:


[server window]
[C:\...\PP4E\Internet\Sockets]$ python multi-server.py
Parent: 8388
Server connected by ('127.0.0.1', 58271) at Sat Apr 24 08:13:27 2010
Child: 8144
Server connected by ('127.0.0.1', 58272) at Sat Apr 24 08:13:29 2010
Child: 8036

[two client windows]
C:\...\PP4E\Internet\Sockets> python echo-client.py
Client received: b"Echo=>b'Hello network world' at Sat Apr 24 08:13:33 2010"

C:\...\PP4E\Internet\Sockets> python echo-client.py localhost Brave Sir Robin
Client received: b"Echo=>b'Brave' at Sat Apr 24 08:13:35 2010"
Client received: b"Echo=>b'Sir' at Sat Apr 24 08:13:35 2010"
Client received: b"Echo=>b'Robin' at Sat Apr 24 08:13:35 2010"

However, this server does not work on standard Windows Python—the whole point
of trying to use multiprocessing in this context—because open sockets are not correctly
pickled when passed as arguments into the new process. Here’s what occurs in the
server windows on Windows 7 with Python 3.1:


C:\...\PP4E\Internet\Sockets> python multi-server.py
Parent: 9140
Server connected by ('127.0.0.1', 58276) at Sat Apr 24 08:17:41 2010
Child: 9628
Process Process-1:
Traceback (most recent call last):
File "C:\Python31\lib\multiprocessing\process.py", line 233, in _bootstrap
self.run()
File "C:\Python31\lib\multiprocessing\process.py", line 88, in run
self._target(*self._args, **self._kwargs)
File "C:\...\PP4E\Internet\Sockets\multi-server.py", line 38, in handleClient
data = connection.recv(1024) # till eof when socket closed

814 | Chapter 12: Network Scripting

Free download pdf