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

(yzsuai) #1
Traceback (most recent call last):
File "C:\...\PP4E\Internet\Sockets\test-stream-modes.py", line 26, in <module>
writer( open('temp', 'wb') ) # FAILS on print: binary mode...
File "C:\...\PP4E\Internet\Sockets\test-stream-modes.py", line 20, in writer
print(99, 'spam')
TypeError: must be bytes or buffer, not str

C:\...\PP4E\Internet\Sockets> test-streams-binary.py
"""
b'"""\r'
99 spam

Traceback (most recent call last):
File "C:\...\PP4E\Internet\Sockets\test-stream-modes.py", line 27, in <module>
writer( open('temp', 'w', 0) ) # FAILS on open: text must be...
ValueError: can't have unbuffered text I/O

The same rules apply to socket wrapper file objects created with a socket’s makefile
method—they must be opened in text mode for print and should be opened in text
mode for input if we wish to receive text strings, but text mode prevents us from using
fully unbuffered file mode altogether:


>>> from socket import *
>>> s = socket() # defaults to tcp/ip (AF_INET, SOCK_STREAM)
>>> s.makefile('w', 0) # this used to work in Python 2.X
Traceback (most recent call last):
File "C:\Python31\lib\socket.py", line 151, in makefile
ValueError: unbuffered streams must be binary

Line buffering


Text-mode socket wrappers also accept a buffering-mode argument of 1 to specify line-
buffering instead of the default full buffering:


>>> from socket import *
>>> s = socket()
>>> f = s.makefile('w', 1) # same as buffering=1, but acts as fully buffered!

This appears to be no different than full buffering, and still requires the resulting file
to be flushed manually to transfer lines as they are produced. Consider the simple socket
server and client scripts in Examples 12-13 and 12-14. The server simply reads three
messages using the raw socket interface.


Example 12-13. PP4E\Internet\Sockets\socket-unbuff-server.py


from socket import * # read three messages over a raw socket
sock = socket()
sock.bind(('', 60000))
sock.listen(5)
print('accepting...')
conn, id = sock.accept() # blocks till client connect


for i in range(3):
print('receiving...')


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