问题
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.
Behold the following test script:
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
The result:
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
It appears that if I don't put a delay of about 0.9s between my connect() attempts, I get this exception.
What is going on?
回答1:
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.
来源:https://stackoverflow.com/questions/24773059/socket-oserror-winerror-10022-when-making-connect-attempts-too-quickly