Example 12-11. PP4E\Internet\Sockets\test-socket_stream_redirect.py
"""
###############################################################################
test the socket_stream_redirection.py modes
###############################################################################
"""
import sys, os, multiprocessing
from socket_stream_redirect import *
###############################################################################
redirected client output
###############################################################################
def server1():
mypid = os.getpid()
conn = initListenerSocket() # block till client connect
file = conn.makefile('r')
for i in range(3): # read/recv client's prints
data = file.readline().rstrip() # block till data ready
print('server %s got [%s]' % (mypid, data)) # print normally to terminal
def client1():
mypid = os.getpid()
redirectOut()
for i in range(3):
print('client %s: %s' % (mypid, i)) # print to socket
sys.stdout.flush() # else buffered till exits!
###############################################################################
redirected client input
###############################################################################
def server2():
mypid = os.getpid() # raw socket not buffered
conn = initListenerSocket() # send to client's input
for i in range(3):
conn.send(('server %s: %s\n' % (mypid, i)).encode())
def client2():
mypid = os.getpid()
redirectIn()
for i in range(3):
data = input() # input from socket
print('client %s got [%s]' % (mypid, data)) # print normally to terminal
###############################################################################
redirect client input + output, client is socket client
###############################################################################
def server3():
mypid = os.getpid()
conn = initListenerSocket() # wait for client connect
file = conn.makefile('r') # recv print(), send input()
for i in range(3): # readline blocks till data
830 | Chapter 12: Network Scripting