Python套接字连接超时问题
我正在尝试编写一个简单的脚本,连接到 freenode IRC 网络(端口 6667 上的 irc.freenode.net),以定期在频道上发布信息。为此,我使用 Python 套接字。这在过去工作得很好,但是现在我遇到了一个奇怪的问题:套接字需要非常长的时间才能连接(如果它确实连接的话)(偶尔会超时)。但是,只有当脚本从文件运行时才会发生这种情况。当直接输入解释器时,它工作正常:
>>> import socket
>>> def f():
>>> s = socket.socket()
>>> print("Connecting")
>>> s.connect(('irc.freenode.net', 6667))
>>> print("Connected")
>>> s.close()
>>> f()
套接字在大约一秒钟内连接,一切都很好。但是,如果我将以下代码放入文件中并运行 python test.py,它会挂在 s.connect
上并且偶尔会超时:
import socket
s = socket.socket()
print("Connecting")
s.connect(('irc.freenode.net', 6667))
print("Connected")
s.close()
我以前从未遇到过此问题。我网络上的其他计算机上也会出现这种情况(也许是网络问题?)。我正在使用Python 3.2。谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
网络总是会出现间歇性问题,您的代码需要处理这些问题。我建议采取两个层面的行动。首先,在
socket.create_connection
上使用timeout=
参数,在放弃之前等待一段时间。然后将套接字打开放入try
except socket.timeout
对中并重试几次,可能在重试之间休眠一两秒。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 onsocket.create_connection
to wait a bit longer before giving up. Then put the socket opening inside atry
except socket.timeout
pair and retry a couple of times, maybe sleeping a second or two between retries.