Sunday, January 31, 2010

Tricky issues with socket.makefile() in Python 3

I have been experimenting with socket.makefile()from Python 3.1.1.
The makefile() method returns a file like object for the socket so that file operations (read, readlines, write, writelines, ...) can be used to send and receive data on the socket.

I have not had much difficulty reading from the returned file object, but I don't understand the behavior when trying to write (send on the socket).  I'm hoping that someone can explain how this is supposed to work.

I find that this works for an established connection on socket s:
fd = s.makefile('wb', buffering = 0)
fd.write("This is a test message\n".encode('ascii'))

A mode of 'rwb' also works.  The object fd is of type SocketIO.

fd = s.makefile('w', buffering = 0) -> ValueError exception
fd = s.makefile('w') -> io.BufferedWriter, which does not send data.
fd = s.makefile('wb') -> io.TextIOWrapper, which does not send data.

The default value of the "buffering" parameter is None, which from my testing has a different result than 0 (zero).

So, questions:
1) Why does buffering = None result in a buffered file object?
2) Are there bugs or incomplete work with socket.makefile(), io.BufferedWriter and io.TextIOWrapper in terms of why the latter two objects are returned, but fail to send data?

If I find out the answers to these questions, I'll post them.

No comments:

Post a Comment