当连接()尝试太快时,Socket OSError [WinError 10022] [英] Socket OSError [WinError 10022] when making connect() attempts too quickly

查看:711
本文介绍了当连接()尝试太快时,Socket OSError [WinError 10022]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个客户需要反复轮询,看看预期的服务器是否在那里,并且优雅地处理可能不会延长的时间。

I have a client that needs to repeatedly poll to see if the expected server is there, and gracefully deal with the fact that it might not be for extended periods of time.

看下面的测试脚本:

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秒,我会收到这个例外。

It appears that if I don't put a delay of about 0.9s between my connect() attempts, I get this exception.

发生了什么?

推荐答案

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

You're using one socket for every connection "attempt". A socket can only be used for one connection. You're actually only making one connection attempt here. When it finally times out the socket gets to a state where you're not allowed to call connect anymore.

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

Create a new socket for each new connection attempt you want to try.

这篇关于当连接()尝试太快时,Socket OSError [WinError 10022]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆