开发者

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(soc开发者_如何学JAVAklist, 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 processing a connect call (nonblocking), connection attempt failed.
  • OOB data is available for reading


A client closing a socket is not exceptional. It is in fact anything but exceptional. You will get various errors in the list of exceptional conditions, but a correctly closed socket is not one of them.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜