I have a client server architecture written in python. Most of the time it works fine, but sometimes, after I stop the server and restart it immediately afterwards, I get the following error:
Accept failed due to : 22 Message Invalid argument, error: [Errno 22] Invalid argument
However, if I wait a few minutes and the start the same script again with no changes it works fine.
This is the loop I use on the server to accept incoming connections from clients:
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('',port))
s.listen(1)
except:
#logError()
while True:
try:
conn, address = s.accept() #THIS ACCEPT FAILS SOMETIMES
multiprocessing.Process(target=HandleConnection, args=(conn, address, messageQueue, taskQueue, IOLock, numberOfConnections, numberOfConnectionsLock,resultsDirectory)).start()
except socket.error, msg:
#logError() -> this except catches the error
Does the port get blocked for some time after I run the server? If so, is there are way to query if the port is blocked and wait until it's unblocked if I want to start the server up again immediately after it just quit?
You need to set SO_REUSEADDR
before binding.
setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
Failing to do so may prevent the socket from binding, thus the error when accept
ing. You would have noticed this error if you hadn't choked exceptions in the first block.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With