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

(yzsuai) #1

Socket basics


Although sockets are one of the most commonly used IPC tools, it’s impossible to fully
grasp their API without also seeing its role in networking. Because of that, we’ll defer
most of our socket coverage until we can explore their use in network scripting in
Chapter 12. This section provides a brief introduction and preview, so you can compare
with the prior section’s named pipes (a.k.a. fifos). In short:



  • Like fifos, sockets are global across a machine; they do not require shared memory
    among threads or processes, and are thus applicable to independent programs.

  • Unlike fifos, sockets are identified by port number, not filesystem path name; they
    employ a very different nonfile API, though they can be wrapped in a file-like object;
    and they are more portable: they work on nearly every Python platform, including
    standard Windows Python.


In addition, sockets support networking roles that go beyond both IPC and this chap-
ter’s scope. To illustrate the basics, though, Example 5-25 launches a server and 5
clients in threads running in parallel on the same machine, to communicate over a
socket—because all threads connect to the same port, the server consumes the data
added by each of the clients.


Example 5-25. PP4E\System\Processes\socket_preview.py


"""
sockets for cross-task communication: start threads to communicate over sockets;
independent programs can too, because sockets are system-wide, much like fifos;
see the GUI and Internet parts of the book for more realistic socket use cases;
some socket servers may also need to talk to clients in threads or processes;
sockets pass byte strings, but can be pickled objects or encoded Unicode text;
caveat: prints in threads may need to be synchronized if their output overlaps;
"""


from socket import socket, AF_INET, SOCK_STREAM # portable socket api


port = 50008 # port number identifies socket on machine
host = 'localhost' # server and client run on same local machine here


def server():
sock = socket(AF_INET, SOCK_STREAM) # ip addresses tcp connection
sock.bind(('', port)) # bind to port on this machine
sock.listen(5) # allow up to 5 pending clients
while True:
conn, addr = sock.accept() # wait for client to connect
data = conn.recv(1024) # read bytes data from this client
reply = 'server got: [%s]' % data # conn is a new connected socket
conn.send(reply.encode()) # send bytes reply back to client


def client(name):
sock = socket(AF_INET, SOCK_STREAM)
sock.connect((host, port)) # connect to a socket port
sock.send(name.encode()) # send bytes data to listener
reply = sock.recv(1024) # receive bytes data from listener


Interprocess Communication | 237
Free download pdf