setblocking in Win32

Robert W. Bill rbill at digisprings.com
Thu Jun 8 17:23:52 EDT 2000


HI,

I have a suspicion on this, but please forgive the guess if I am wrong.

I think non-blocking means that an exception is raised immediately if the
socket cannot act on the call at that very moment.  In other words, if you 
say sock.accept(), and there is not an immediate connection, the
EWOULDBLOCK exception is raised so that the socket does not block
anything.  I think the EWOULDBLOCK is error # 10035 on WinNT- the error
code you are getting.  This means that what you have done so far is good
news- the socket is doing what it is supposed to do.

The trick is to pass through the exception, possibly like thus:

import socket
from errno import EALREADY, EINPROGRESS, EWOULDBLOCK, ECONNRESET, ENOTCONN

try: 
    conn, addr = sock.accept()
    print "connection received"
    handle_connect(conn, addr) # some method you've made
except socket.error, e:
    if why[0] == EWOULDBLOCK:
        print "socket would have blocked and I couldn't wait"
    else:  # in case it is a different error situation
        raise socket.error, e
        sock.close()

The next catch is that you now must loop through this to catch a
connection, so it is good to add a select to be nicer to the cpu
i.e.:

import socket
import select
from errno import EWOULDBLOCK, etc....

sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.setblocking(0)
sock.bind("", 8002)
 
while 1:
    select.select([sock],[sock],[sock],2) # 2 is the arbitrary timeout
    try: 
        conn, addr = sock.accept()
        print "connection received", conn
        handle_connect(conn, addr)
    except socket.error, e:
        if why[0] == EWOULDBLOCK:
            print "would block, so proceeding after interupting socket"
        else:
            raise socket.error, e
            sock.close()

I hope this helps.

Robert

On Thu, 8 Jun 2000 jkingry at my-deja.com wrote:

> Hi, I think I'm going to be told what I don't what to hear, but from
> the error below, I think I have surmised that trying to set non-
> blocking on a socket in a Win32 environment doesn't work.
> 
> Are there any work arounds?
> 
> Joe
> 
> Traceback (innermost last):
>   File "D:\Prog\Python\Lib\threading.py", line 376, in __bootstrap
>     self.run()
>   File "D:\Prog\Python\Lib\threading.py", line 364, in run
>     apply(self.__target, self.__args, self.__kwargs)
>   File "io.py", line 80, in run
>     sock,(address,port) = server.accept()
>   File "D:\Prog\Python\Lib\plat-win\socket.py", line 36, in accept
>     sock, addr = self._sock.accept()
> error: (10035, 'winsock error')
> 
> 
> Sent via Deja.com http://www.deja.com/
> Before you buy.
> 





More information about the Python-list mailing list