连接尝试过快导致Socket OSError [WinError 10022]

1 投票
1 回答
4651 浏览
提问于 2025-04-18 13:30

我有一个客户需要不断检查预期的服务器是否在线,并且要优雅地处理服务器可能长时间不在线的情况。

看看下面这个测试脚本:

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秒的延迟,就会出现这个异常。

这是怎么回事呢?

1 个回答

1

你每次连接尝试都在用同一个插口(socket)。其实,一个插口只能用来建立一个连接。你这里实际上只是在尝试建立一次连接。当这个连接尝试超时后,这个插口就会进入一种状态,你就不能再用它去调用 connect 了。

每次想要尝试新的连接时,记得创建一个新的插口。

撰写回答