我有一个客户端需要反复轮询以查看预期的服务器是否存在,并优雅地处理它可能不会延长的事实时间。套接字OSError [WinError 10022]使连接()尝试过快
看哪以下测试脚本:
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.9S的延迟,我得到这个异常。
这是怎么回事?
我想我已经看到过这样的事情。它实际上是MS Windows中的一个设置,可以防止短时间内建立多个连接。我不记得理由,但它必须保护他人免受计算机上的不当行为。你可以通过注册表来配置它。 –
有趣,这是有道理的。我不打算通过我的程序来触摸这个注册表设置,我只需设置延迟即可。但是,我想知道是否可以找到一些有关延迟可能的文档以及其他任何考虑事项。我不喜欢只是盲目地设置一个延迟,并希望它的工作:) – Lewis