Why do socket.makefile objects fail after the first read for UDP sockets?

Posted by Eli Courtwright on Stack Overflow See other posts from Stack Overflow or by Eli Courtwright
Published on 2010-04-17T22:55:59Z Indexed on 2010/04/17 23:03 UTC
Read the original article Hit count: 365

Filed under:
|
|

I'm using the socket.makefile method to create a file-like object on a UDP socket for the purposes of reading. When I receive a UDP packet, I can read the entire contents of the packet all at once by using the read method, but if I try to split it up into multiple reads, my program hangs.

Here's a program which demonstrates this problem:

import socket
from sys import argv

SERVER_ADDR = ("localhost", 12345)

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(SERVER_ADDR)
f = sock.makefile("rb")

sock.sendto("HelloWorld", SERVER_ADDR)

if "--all" in argv:
    print f.read(10)
else:
    print f.read(5)
    print f.read(5)

If I run the above program with the --all option, then it works perfectly and prints HelloWorld. If I run it without that option, it prints Hello and then hangs on the second read. I do not have this problem with socket.makefile objects when using TCP sockets.

Why is this happening and what can I do to stop it?

© Stack Overflow or respective owner

Related posts about python

Related posts about udp