我正在尝试开发一个简单的套接字服务器,它具有非阻塞接受(使用settimeout(,但我希望能够使用Ctrl-C(键盘中断(停止它。
我的代码是这样的:
import socket
host = '127.0.0.1'
port = 5000
s = socket.socket()
s.settimeout(1)
s.bind((host, port))
s.listen(1)
print('Server started')
while True:
try:
conn, addr = s.accept()
except socket.timeout:
pass
except Exception as exc:
print(str(exc))
print('Server closing')
s.close()
break
except KeyboardInterrupt:
print('Server closing')
s.close()
break
else:
print('Connection from', addr)
但是 KeyboardInterrupt 永远不会被捕获,因为它发生在 socket.timeout 异常处理程序内。这是按 Ctrl-C 时的输出
c:UsersJMatosMEOCloudPython>python file_server.py
Server started
Traceback (most recent call last):
File "file_server.py", line 40, in <module>
conn, addr = s.accept()
File "C:Python35-32libsocket.py", line 195, in accept
fd, addr = self._accept()
socket.timeout: timed out
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "file_server.py", line 40, in <module>
conn, addr = s.accept()
KeyboardInterrupt
有没有办法在套接字中捕获键盘中断异常.timeout 异常处理程序?
我的环境是Windows 7P + SP1 x64,Python 3.5.2 32b。
提前感谢,
JM
问题不在于套接字超时。问题在于您希望抛出异常的位置。 将代码更改为:
try:
while True:
try:
conn, addr = s.accept()
except socket.timeout:
pass
except Exception as exc:
print(str(exc))
print('Server closing')
s.close()
break
else:
print('Connection from', addr)
except KeyboardInterrupt:
print('Server closing')
s.close()