Non-blocking socket, error always

sock.setblocking(0) try: data = sock.recv(1024) except socket.error, e: if e.args[0] == errno.EWOULDBLOCK: print 'EWOULDBLOCK' else: if not data: #recv over sock.close() print 'close=================' else: print 'recv ---data---------' poem += data 

all of the above code is in a loop.using a non-blocking socket (just want to check the "non-blocking socket") to get the data. But always type EWOULDBLOCK, I don’t know why?

+6
source share
2 answers

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) # short delay, no tight loops else: print e break 

For this type, select unit is generally suitable.

+9
source

An exception is thrown by design because you are using non-blocking IO .

The main mechanical difference is that send, recv, connect, and accept can return without any action. You have (of course) a number of options. You can check the return code and error codes and generally drive yourself crazy.

Quote from Python document

If you run man errno 3 , you will see a description of EWOULDBLOCK . An exception is reasonable since no data is available.

+3
source

Source: https://habr.com/ru/post/921282/


All Articles