问题
I wrote a TCP server using Python Twisted to send/receive binary data from clients.
When a client close their application or calls the abortConnection
method, I get the connectionLost
event normally but when the client disconnects unexpectedly, I don't get the disconnect event, therefore, I can't remove the disconnected client from the queue.
By unexpected disconnect I mean disabling the network adapter or lost the network connection somehow.
My question is, how can I handle this sort of unexpected connection losts?
回答1:
Enabling TCP keepalive on your socket should fix this.
By default this is disabled and thus if the connection is broken client and server will never find out the connection is dead and simply assume there is no packets being send. A keepalive will send a 'heartbeat' each x interval to see if the connection is still alive.
Read more and check how to do it here: How to use TCP Keepalive with Endpoints in Twisted?
回答2:
The only way to support a cross-platform unexpected disconnection (unplug) is to implement a application-level ping message to ping clients in a specific interval.
来源:https://stackoverflow.com/questions/31903574/twisted-unexpected-connection-lost