简体   繁体   中英

Python sockets connection timeout problem

I'm trying to write a simple script that connects to the freenode IRC network (irc.freenode.net on port 6667) to periodically post information on a channel. To do this, I am employing Python sockets. This has worked fine in the past, however now I am experiencing a strange problem: the socket takes an incredibly long time to connect if it does at all (it occasionally times out). However, this only happens when the script is run from a file. When typed into the interpretor directly 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 connects in about a second and everything is fine. However, if I put the following code in a file and run python test.py , it hangs on s.connect and occasionally times out:

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 occurs on other computers on my network (maybe it's network problem?). I'm using Python 3.2. Thanks.

Networks always have intermittent problems and your code will need to deal with them. I suggest two levels of action. First, use the timeout= argument on socket.create_connection to wait a bit longer before giving up. Then put the socket opening inside a try except socket.timeout pair and retry a couple of times, maybe sleeping a second or two between retries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM