Python 2.7, Windows XP. I have a server that sends messages to client(s). I use select module to check for sockets ready to receive, as well as to catch exceptional conditions. I was under the impression that if a client closed a socket, select() would return said socket in the socket list of exceptional conditions, but it doesn't seem to be doing so:
lin, lout, lex = select.select(socklist, socklist, socklist)
for sock in lin:
# handle incoming messages
for sock in lout:
# send updates
for sock in lex:
# shut down server-side objects for particular client
What would be the best way for the server to determine whether the client is still connected? The server is not always sending data, so I would like not to have to rely on a socket.send() to test whether the client is still there.
A closed socket is not an exception (error) condition. What will happen is the socket will be in the read list (lin) and when you read you will get 0 bytes. This means the other end has closed the socket.
Update:
In normal practice you will never see anything in the except list and can safely ignore it. It is for rarely used things like out-of-band (OOB) and such.
Answer to question updates:
Reliably and quickly detecting that the other end of the socket has gone away can be tricky. If it's important to detect it reliably, always and in a timely fashion then you should use a higher level mechanism such as keepalive/heartbeat.
If the client does a clean shutdown of the socket, then you should see the socket in the read list. Reading from the socket will return 0 bytes which indicates the socket is closed (EOF).
The exact definition of "exceptional conditions" on a socket depends on the underlying implementation. For Windows XP, the underlying implementation is the WinSock select function and exceptional conditions include:
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