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

(yzsuai) #1

import sys, os
from threading import Thread


mode = int(sys.argv[1])
if mode == 1: # run server in this process
server()
elif mode == 2: # run client in this process
client('client:process=%s' % os.getpid())
else: # run 5 client threads in process
for i in range(5):
Thread(target=client, args=('client:thread=%s' % i,)).start()


Let’s run this script on Windows, too (again, this portability is a major advantage of
sockets). First, start the server in a process as an independently launched program in
its own window; this process runs perpetually waiting for clients to request connections
(and as for our prior pipe example you may need to use Task Manager or a window
close to kill the server process eventually):


C:\...\PP4E\System\Processes> socket-preview-progs.py 1

Now, in another window, run a few clients in both processes and thread, by launching
them as independent programs—using 2 as the command-line argument runs a single
client process, but 3 spawns five threads to converse with the server on parallel:


C:\...\PP4E\System\Processes> socket-preview-progs.py 2
client got: [b"server got: [b'client:process=7384']"]

C:\...\PP4E\System\Processes> socket-preview-progs.py 2
client got: [b"server got: [b'client:process=7604']"]

C:\...\PP4E\System\Processes> socket-preview-progs.py 3
client got: [b"server got: [b'client:thread=1']"]
client got: [b"server got: [b'client:thread=2']"]
client got: [b"server got: [b'client:thread=0']"]
client got: [b"server got: [b'client:thread=3']"]
client got: [b"server got: [b'client:thread=4']"]

C:\..\PP4E\System\Processes> socket-preview-progs.py 3
client got: [b"server got: [b'client:thread=3']"]
client got: [b"server got: [b'client:thread=1']"]
client got: [b"server got: [b'client:thread=2']"]
client got: [b"server got: [b'client:thread=4']"]
client got: [b"server got: [b'client:thread=0']"]

C:\...\PP4E\System\Processes> socket-preview-progs.py 2
client got: [b"server got: [b'client:process=6428']"]

Socket use cases


This section’s examples illustrate the basic IPC role of sockets, but this only hints at
their full utility. Despite their seemingly limited byte string nature, higher-order use
cases for sockets are not difficult to imagine. With a little extra work, for instance:


Interprocess Communication | 239
Free download pdf