select.select()不会在套接字上遇到异常情况吗? [英] select.select() does not catch exceptional condition on socket?

查看:178
本文介绍了select.select()不会在套接字上遇到异常情况吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 2.7,Windows XP.我有一台将消息发送到客户端的服务器.我使用select模块来检查准备好接收的套接字,以及捕获异常情况.我的印象是,如果客户端关闭了套接字,则select()会在异常情况下的套接字列表中返回该套接字,但似乎并非如此:

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

服务器确定客户端是否仍处于连接状态的最佳方法是什么?服务器并不总是发送数据,因此我不想不必依靠socket.send()来测试客户端是否仍然存在.

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.

推荐答案

关闭的套接字不是例外(错误)情况.将会发生的是套接字将在读取列表(lin)中,并且在您读取时将得到0个字节.这意味着另一端已关闭插座.

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.

更新:

通常情况下,您不会在例外列表中看到任何东西,可以放心地忽略它.它用于诸如带外(OOB)之类的很少使用的东西.

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.

回答更新问题:

可靠且快速地检测到插座的另一端已消失可能很棘手.如果重要的一点是要始终,及时地可靠地进行检测,则应该使用更高级别的机制,例如keepalive/heartbeat.

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.

如果客户端完全关闭了套接字,那么您应该在读取列表中看到该套接字.从套接字读取将返回0个字节,表示套接字已关闭(EOF).

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

这篇关于select.select()不会在套接字上遇到异常情况吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆