2014-07-16 69 views
1

我有一個客戶端需要反覆輪詢以查看預期的服務器是否存在,並優雅地處理它可能不會延長的事實時間。套接字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的延遲,我得到這個異常。

這是怎麼回事?

+0

我想我已經看到過這樣的事情。它實際上是MS Windows中的一個設置,可以防止短時間內建立多個連接。我不記得理由,但它必須保護他人免受計算機上的不當行爲。你可以通過註冊表來配置它。 –

+0

有趣,這是有道理的。我不打算通過我的程序來觸摸這個註冊表設置,我只需設置延遲即可。但是,我想知道是否可以找到一些有關延遲可能的文檔以及其他任何考慮事項。我不喜歡只是盲目地設置一個延遲,並希望它的工作:) – Lewis

回答

0

您對每個連接「嘗試」都使用一個套接字。套接字只能用於一個連接。你實際上只在這裏做一次連接嘗試。當它最終超時時,套接字就會處於不允許再撥打connect的狀態。

爲每個想要嘗試的新連接嘗試創建一個新套接字。

+0

甜,我確實可以迅速啓動connect()嘗試,如果我每次創建一個新的套接字。我沒有關注我的代碼實際上只是進行一次連接嘗試,也不知道爲什麼如果每次使用相同的套接字時都需要這種看似任意的延遲。 – Lewis

+0

第二次在套接字上調用'connect'不會嘗試第二次連接。這就是TCP套接字的工作原理。 –

+0

我修改了我的客戶端,因此它嘗試連接一次,然後等待10秒,然後嘗試再次連接,都在同一個套接字上。在十幾歲的等待期間,我啓動了主持人。客戶端第二次成功連接。我仍然不遵循它不嘗試第二次連接的方式。它確實看起來像。 – Lewis

相關問題