套接字OSError 使连接()尝试过快

我有一个客户端需要重复轮询,看看是否有预期的服务器,并优雅地处理这个事实,可能不是很长的时间。

看下面的testing脚本:

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 

看来,如果我不把连接()尝试之间的延迟大约0.9秒,我得到这个exception。

到底是怎么回事?

Solutions Collecting From Web of "套接字OSError 使连接()尝试过快"

您为每个连接“尝试”使用一个套接字。 套接字只能用于一个连接。 你实际上只是在这里做一个连接尝试。 当它最终超时,套接字到达一个你不允许调用connect

为每个想要尝试的新连接创建一个新套接字。