Socket OSError [WinError 10022]在使connect()尝试太快时

时间:2014-07-16 05:46:54

标签: python windows sockets exception networking

我有一个客户端需要重复轮询以查看预期的服务器是否存在,并优雅地处理它可能不会持续很长一段时间的事实。

看下面的测试脚本:

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 个答案:

答案 0 :(得分:0)

您正在为每个连接“尝试”使用一个套接字。套接字只能用于一个连接。你实际上只是在这里进行一次连接尝试。当它最终超时时,套接字进入一个不允许再调用connect的状态。

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