The socket is non-blocking so recv()
will raise an exception if there is no data to read. Note that errno.EWOULDBLOCK = errno.EAGAIN = 11. This is Python's (well the OS really) way of telling you to try the recv()
again later.
I note that you close the socket each time you get this exception. That's not going to help at all. Your code should be 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) # short delay, no tight loops
else:
print e
break
For this sort of thing, the select
module is usually the way to go.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…