I'm working on a Python script with a client/server socket. After searching for alternate solutions, I'm not sure if my solution is correct or the best.
I have read these posts :
Python handling socket.error: [Errno 104] Connection reset by peer
Asyncio detecting disconnect hangs
Their solutions do not work for me, but I have the following .I'm not sure if that it's correct or clean.
try:
# See if client has disconnected.
try:
data = (await asyncio.wait_for(client_reader.readline(),timeout=0.01))
except ConnectionResetError, ConnectionAbortedError) as e:
break # Client disconnected
except TimeoutError:
pass # Client hasn't disconnect
If i don't use except for ConnectionResetError, I get an error because the data raises connectionReset when I kill the client.
Is it a good solution to detect an irregular client disconnection ?
ps : Thank you Prune for cleaned up wording and grammar.
As long as you are not interacting with the socket, you don't know if it's still connected or not. The proper way to handle disconnections is not to checks the state of the socket, but to verify if a read or write operation failed because of such error.
Usually, one is always at least awaiting for a read() on a socket, this is where one should look for disconnections. When the exception happens, the stream will be detected as closed and propagate the exception to any other task awaiting on an operation on this socket. It means that if you have concurrent operations on one stream, you must expect this exception to be raised anywhere, and handle it everywhere in your code.
About the exceptions caught: Checking for a ConnectionError is the best solution, it's a parent class of all exceptions related to a connection (ConnectionAbortedError, ConnectionResetError, etc).
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