non-blocking sockets

Paul Sidorsky paulsid at shaw.ca
Tue Apr 23 13:46:14 EDT 2002


so very tired wrote:

> When trying to read from a socket, I don't want it hanging, so I set it to
> non-blocking by calling
> 
> setblocking(0)
> 
> but then when I try to read from it and there is no data in the socket, I
> get an error. I tried this in both windows and linux and in both I get an
> error and the program stops. It says there's an exception but it doesn't
> say the name of the exception so I can't even try to catch.
> Does anyone know how I can check if there's data coming from a socket
> connection without hanging or having the program barf on me?

The error you need to catch is called "error" in the socket module, i.e.
socket.error.  It's described at the top of section 7.2 in the library
reference.  

Depending on what you're doing you might want to check the errno to see
that the problem is only that there's no data available and not
something more serious.  A blanket "except socket.error:  pass" will
work well enough to get you started, though.

BTW for anything heavy-duty, using select as others have recommended is
probably a better solution.

-- 
======================================================================
Paul Sidorsky                                          Calgary, Canada
paulsid at shaw.ca                        http://members.shaw.ca/paulsid/





More information about the Python-list mailing list