在智能家居项目hestia中,遇到一个关于python socket编程的小问题。发现在python socket客户端一端,在服务端断开时,没有抛出异常。
[code lang=”python”]
try:
msg = _sFile.readline()
except socket.error, e:
logging.info("socket exception" + e.message)
_reconnect()
[/code]
翻阅文档后,发现python socket分为阻塞式和非阻塞式。默认初始化的socket是阻塞式的,在阻塞式下,如果socket断开链接,将会返回空串。官方解释如下:
socket.
setblocking
(flag)- Set blocking or non-blocking mode of the socket: if flag is 0, the socket is set to non-blocking, else to blocking mode. Initially all sockets are in blocking mode. In non-blocking mode, if a
recv()
call doesn’t find any data, or if asend()
call can’t immediately dispose of the data, anerror
exception is raised; in blocking mode, the calls block until they can proceed.s.setblocking(0)
is equivalent tos.settimeout(0.0)
;s.setblocking(1)
is equivalent tos.settimeout(None)
.
故修改代码如下:
[code lang=”python”]
try:
msg = _sFile.readline()
if msg == "":
_reconnect()
except socket.error, e:
logging.info("socket exception" + e.message)
_reconnect()
[/code]
文章来源:胡小旭 => Python socket网络编程之阻塞与非阻塞模式