non-blocking socket connects?

Dave Brueck dave at pythonapocrypha.com
Sun May 25 02:28:16 EDT 2003


On Sun, 25 May 2003, Gary Stephenson wrote:

> I'm trying to do a non-blocking socket connect(), but the following code
> never completes:
>
>     def _connect( self ) :
>         print "connecting to ", self.addr, self.port
>         while True :
>             try :
>                 self.sock.connect( (self.addr, self.port) )
>             except socket.error :
>                 #  _always_ occurs
>                 yield None
>                 continue
>             except :
>                 #  _never_ occurs
>                 print "connection error"
>             break
>         print "connected"
>
> whereas this code works just fine:
>
>     def _connect( self ) :
>         self.sock.setblocking( True )
>         self.sock.connect( (self.addr, self.port) )
>         self.sock.setblocking( False )
>
> Can anybody please enlighten me as to what I'm doing wrong with the first
> version?

Hi Gary,

Non-blocking connect is a little weird - you call connect() once and only
once, and then know the connection has succeeded when the socket becomes
"writable" (i.e. when select/poll on that socket indicates that at least
some output can happen without blocking).

Lemme know if you need more details,
-Dave





More information about the Python-list mailing list