Socket connection

Donn Cave donn at u.washington.edu
Fri Mar 7 02:10:34 CET 2003


Quoth Jp Calderone <exarkun at intarweb.us>:
| On Thu, Mar 06, 2003 at 03:32:15PM -0600, sik0fewl wrote:
|> 
|> I'm having some problems with some socket/thread code.
|> 
|> What I'm doing is starting another thread to do the actual connect() so 
|> that my process doesn't block while connect does socket.getaddrinfo().
|> 
|> What I have works fine if the host is localhost, otherwise it doesn't 
|> seem to ever connect.
|> 
|> Here's the basis of my code:
|> 
|> -----
|> 
|> def threaded_connect(sock, address, port = None):
|>     try:
|>         sock.connect((address, port))
|>     except:
|>         pass
|> 
|> x = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|> x.setblocking(0)
|> 
|> thread.start_new_thread(threaded_connect, (x, 'www.hotmail.com', 80))
|> 
|> while 1:
|> 	# then I do select that waits for x to become writable
|> 	# (ie, connected)
|> 
|> -----
|> 
|> Like I said, the select() works fine when connecting to localhost, but 
|> when I try any other address (like www.hotmail.com) the select keeps 
|> timing out and x never becomes connected.
|
|   You've made the socket non-blocking.  This means socket.connect() will
| return right away, *even if it has not yet connected*.  Even leaving this
| aside, your code has a race condition, nothing says that the connection in
| the thread will be made before the select() loop begins.

I think that's as it should be, and the select is supposed to deal
with it.  But since he also ignores exceptions from the connect()
attempt, he turns every possible error into a silent select timeout.

|   I'd recommend -either- using threads -or- using non-blocking sockets, not
| both (I'd further recommend not using threads).
|
|   There are libraries available to make this sort of programming easier. 
| You might check out Twisted - http://www.twistedmatrix.com/

It sure seems to be the rage this week.  Do you know if it has the
asynchronous DNS lookup he'll need, to replace the threads?

	Donn Cave, donn at u.washington.edu




More information about the Python-list mailing list