Socket connection
Jp Calderone
exarkun at intarweb.us
Thu Mar 6 18:13:53 EST 2003
On Thu, Mar 06, 2003 at 03:32:15PM -0600, sik0fewl wrote:
> Hi,
>
> 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.
It's hard to say exactly why x never shows up in your select, partly
because threaded programs are difficult to predict, and partly because you
haven't included the select-using code in the example.
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/
Jp
--
up 3 days, 15:58, 6 users, load average: 0.04, 0.05, 0.00
More information about the Python-list
mailing list