【发布时间】:2014-07-16 17:23:59
【问题描述】:
我有一个客户端需要反复轮询以查看预期的服务器是否在那里,并优雅地处理它可能长时间不存在的事实。
看下面的测试脚本:
import socket, time
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(0.1)
delay = 2
connected = False
while not connected:
try:
s.connect(("localhost", 50000)) # I'm running my test server locally
connected = True
except socket.timeout:
print("Timed out. Waiting " + str(round(delay, 1)) + "s before next attempt.")
time.sleep(delay)
delay -= 0.1
结果:
Timed out. Waiting 2s before next attempt.
Timed out. Waiting 1.9s before next attempt.
Timed out. Waiting 1.8s before next attempt.
Timed out. Waiting 1.7s before next attempt.
Timed out. Waiting 1.6s before next attempt.
Timed out. Waiting 1.5s before next attempt.
Timed out. Waiting 1.4s before next attempt.
Timed out. Waiting 1.3s before next attempt.
Timed out. Waiting 1.2s before next attempt.
Timed out. Waiting 1.1s before next attempt.
Timed out. Waiting 1.0s before next attempt.
Timed out. Waiting 0.9s before next attempt.
Traceback (most recent call last):
File "C:/Users/Lewis/Desktop/sockettest.py", line 11, in <module>
s.connect(("localhost", 50000))
OSError: [WinError 10022] An invalid argument was supplied
看来,如果我在 connect() 尝试之间没有延迟大约 0.9 秒,我就会得到这个异常。
发生了什么事?
【问题讨论】:
-
我想我见过这样的事情。它实际上是 MS Windows 中的一个设置,可以防止在短时间内建立许多连接。我不记得基本原理,但它与保护他人免受您计算机上行为不端的软件的侵害有关。不过,您可以通过注册表进行配置。
-
有趣,有道理。我不打算用我的程序来接触这个注册表设置,我只需设置一个延迟就可以了。但是,我想看看我是否可以找到一些关于延迟可能是什么的文档,以及任何其他注意事项。我不喜欢盲目地设置延迟并希望它有效:)
标签: python windows sockets exception networking