我有一个需要反复调查,看是否预期的服务器是存在的,且与事实,它可能不适合长时间优雅地处理客户端。
看哪,下面的测试脚本:
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的延迟,我得到这个例外。
到底是怎么回事?