Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select.select() does not catch exceptional condition on socket?

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.

like image 709
Shaunak Amin Avatar asked Dec 21 '22 16:12

Shaunak Amin


2 Answers

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).

like image 179
kanaka Avatar answered Dec 28 '22 10:12

kanaka


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 processing a connect call (nonblocking), connection attempt failed.
  • OOB data is available for reading
like image 32
srgerg Avatar answered Dec 28 '22 08:12

srgerg