sock.close() # up to 1024 bytes in message
print('client got: [%s]' % reply)
if name == 'main':
from threading import Thread
sthread = Thread(target=server)
sthread.daemon = True # don't wait for server thread
sthread.start() # do wait for children to exit
for i in range(5):
Thread(target=client, args=('client%s' % i,)).start()
Study this script’s code and comments to see how the socket objects’ methods are used
to transfer data. In a nutshell, with this type of socket the server accepts a client con-
nection, which by default blocks until a client requests service, and returns a new socket
connected to the client. Once connected, the client and server transfer byte strings by
using send and receive calls instead of writes and reads, though as we’ll see later in the
book, sockets can be wrapped in file objects much as we did earlier for pipe descriptors.
Also like pipe descriptors, unwrapped sockets deal in binary bytes strings, not text
str; that’s why string formatting results are manually encoded again here.
Here is this script’s output on Windows:
C:\...\PP4E\System\Processes> socket_preview.py
client got: [b"server got: [b'client1']"]
client got: [b"server got: [b'client3']"]
client got: [b"server got: [b'client4']"]
client got: [b"server got: [b'client2']"]
client got: [b"server got: [b'client0']"]
This output isn’t much to look at, but each line reflects data sent from client to server,
and then back again: the server receives a bytes string from a connected client and
echoes it back in a larger reply string. Because all threads run in parallel, the order in
which the clients are served is random on this machine.
Sockets and independent programs
Although sockets work for threads, the shared memory model of threads often allows
them to employ simpler communication devices such as shared names and objects and
queues. Sockets tend to shine brighter when used for IPC by separate processes and
independently launched programs. Example 5-26, for instance, reuses the server
and client functions of the prior example, but runs them in both processes and threads
of independently launched programs.
Example 5-26. PP4E\System\Processes\socket-preview-progs.py
"""
same socket, but talk between independent programs too, not just threads;
server here runs in a process and serves both process and thread clients;
sockets are machine-global, much like fifos: don't require shared memory
"""
from socket_preview import server, client # both use same port number
238 | Chapter 5: Parallel System Tools