我有一個客戶端需要反覆輪詢以查看預期的服務器是否存在,並優雅地處理它可能不會延長的事實時間。套接字OSError [WinError 10022]使連接()嘗試過快
看哪以下測試腳本:
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的延遲,我得到這個異常。
這是怎麼回事?
我想我已經看到過這樣的事情。它實際上是MS Windows中的一個設置,可以防止短時間內建立多個連接。我不記得理由,但它必須保護他人免受計算機上的不當行爲。你可以通過註冊表來配置它。 –
有趣,這是有道理的。我不打算通過我的程序來觸摸這個註冊表設置,我只需設置延遲即可。但是,我想知道是否可以找到一些有關延遲可能的文檔以及其他任何考慮事項。我不喜歡只是盲目地設置一個延遲,並希望它的工作:) – Lewis