The socket is not blocked, so recv()
will throw an exception if there is no data to read. Note that errno.EWOULDBLOCK = errno.EAGAIN = 11. This is Python (well, actually the OS) telling you to try recv()
again.
I note that you close the socket every time you get this exception. This will not help at all. Your code should look something like this:
import socket, errno, time sock = socket.socket() sock.connect(('hostname', 1234)) sock.setblocking(0) while True: try: data = sock.recv(1024) if not data: print "connection closed" sock.close() break else: print "Received %d bytes: '%s'" % (len(data), data) except socket.error, e: if e.args[0] == errno.EWOULDBLOCK: print 'EWOULDBLOCK' time.sleep(1)
For this type, select
unit is generally suitable.
source share