I'm writing an app in Python 2.7.5 using the raw socket interface (import socket
).
I need to know if there's a way I can either register some sort of event, or easily test at a regular interval, if a TCP socket connection is still connected and established.
Most of the advice I've found says things like "just try to read from it; if it's closed you'll get an error or no bytes." However, sometimes I'm not ready to read
from it but I still want to know if the socket gets closed, so for example I can manually reconnect immediately.
Also, read
ing from the socket would remove the bytes read from the buffer, so read
ing simply to test for connection "liveness" doesn't seem feasible.
Having a background thread to check for connection liveness would be OK with me. That thread could check say once per second to see if the connection is live; if it is dropped, then it could call a function, or set a variable or some other thing so that the app knows the connection closed. Knowing WHY it closed (reset by peer, timeout, etc) would be even more useful....
Any advice on this?