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

(yzsuai) #1

msg = conn.recv(1024) # blocks till data received
print(msg) # gets all print lines at once unless flushed


The client in Example 12-14 sends three messages; the first two over a socket wrapper
file, and the last using the raw socket; the manual flush calls in this are commented out
but retained so you can experiment with turning them on, and sleep calls make the
server wait for data.


Example 12-14. PP4\Internet\Sockets\socket-unbuff-client.py


import time # send three msgs over wrapped and raw socket
from socket import *
sock = socket() # default=AF_INET, SOCK_STREAM (tcp/ip)
sock.connect(('localhost', 60000))
file = sock.makefile('w', buffering=1) # default=full buff, 0=error, 1 not linebuff!


print('sending data1')
file.write('spam\n')
time.sleep(5) # must follow with flush() to truly send now
#file.flush() # uncomment flush lines to see the difference


print('sending data2')
print('eggs', file=file) # adding more file prints does not flush buffer either
time.sleep(5)
#file.flush() # output appears at server recv only upon flush or exit


print('sending data3')
sock.send(b'ham\n') # low-level byte string interface sends immediately
time.sleep(5) # received first if don't flush other two!


Run the server in one window first and the client in another (or run the server first in
the background in Unix-like platforms). The output in the server window follows—
the messages sent with the socket wrapper are deferred until program exit, but the raw
socket call transfers data immediately:


C:\...\PP4E\Internet\Sockets> socket-unbuff-server.py
accepting...
receiving...
b'ham\n'
receiving...
b'spam\r\neggs\r\n'
receiving...
b''

The client window simply displays “sending” lines 5 seconds apart; its third message
appears at the server in 10 seconds, but the first and second messages it sends using
the wrapper file are deferred until exit (for 15 seconds) because the socket wrapper is
still fully buffered. If the manual flush calls in the client are uncommented, each of the
three sent messages is delivered in serial, 5 seconds apart (the third appears immediately
after the second):


836 | Chapter 12: Network Scripting

Free download pdf