Python socket connection timeout issue

I am trying to write a simple script that connects to the freenode IRC network (irc.freenode.net on port 6667) to periodically publish channel information. For this, I use Python sockets. This worked fine in the past, but now I have a strange problem: the socket takes an incredibly long time to connect, if it does at all (it leaves from time to time). However, this only happens when the script is run from a file. When typed directly into the interpreter, it works fine:

>>> import socket >>> def f(): >>> s = socket.socket() >>> print("Connecting") >>> s.connect(('irc.freenode.net', 6667)) >>> print("Connected") >>> s.close() >>> f() 

The socket is connected in about a second, and everything is in order. However, if I put the following code in a file and run python test.py , it hangs on s.connect and from time to time:

 import socket s = socket.socket() print("Connecting") s.connect(('irc.freenode.net', 6667)) print("Connected") s.close() 

I have never had this problem before. This also happens on other computers on my network (perhaps a network problem?). I am using Python 3.2. Thank you

+4
source share
1 answer

There are always unsustainable problems in networks, and your code will have to deal with them. I offer two levels of action. First use the timeout= argument on socket.create_connection to wait a little longer before giving up. Then place the hole in the try except socket.timeout and try again a couple of times, perhaps sleep a second or two between attempts.

+1
source

All Articles