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

(yzsuai) #1

"""
sock = socket(AF_INET, SOCK_STREAM)
sock.connect((host, port)) # caller operates in client mode
file = sock.makefile('w') # file interface: text, buffered
sys.stdout = file # make prints go to sock.send
return sock # if caller needs to access it raw


def redirectIn(port=port, host=host):
"""
connect caller's standard input stream to a socket for GUI to provide
"""
sock = socket(AF_INET, SOCK_STREAM)
sock.connect((host, port))
file = sock.makefile('r') # file interface wrapper
sys.stdin = file # make input come from sock.recv
return sock # return value can be ignored


def redirectBothAsClient(port=port, host=host):
"""
connect caller's standard input and output stream to same socket
in this mode, caller is client to a server: sends msg, receives reply
"""
sock = socket(AF_INET, SOCK_STREAM)
sock.connect((host, port)) # or open in 'rw' mode
ofile = sock.makefile('w') # file interface: text, buffered
ifile = sock.makefile('r') # two file objects wrap same socket
sys.stdout = ofile # make prints go to sock.send
sys.stdin = ifile # make input come from sock.recv
return sock


def redirectBothAsServer(port=port, host=host):
"""
connect caller's standard input and output stream to same socket
in this mode, caller is server to a client: receives msg, send reply
"""
sock = socket(AF_INET, SOCK_STREAM)
sock.bind((host, port)) # caller is listener here
sock.listen(5)
conn, addr = sock.accept()
ofile = conn.makefile('w') # file interface wrapper
ifile = conn.makefile('r') # two file objects wrap same socket
sys.stdout = ofile # make prints go to sock.send
sys.stdin = ifile # make input come from sock.recv
return conn


To test, the script in Example 12-11 defines five sets of client/server functions. It runs
the client’s code in process, but deploys the Python multiprocessing module we met
in Chapter 5 to portably spawn the server function’s side of the dialog in a separate
process. In the end, the client and server test functions run in different processes, but
converse over a socket that is connected to standard streams within the test script’s
process.


Making Sockets Look Like Files and Streams | 829
Free download pdf