我正在python中进行套接字编程,我想检测服务器端的客户端套接字断开 .

客户:

socket.connect(host, port)
try:
    """ send something to server and get response from the server"""
except KeyboardInterrupt:
    socket.shutdown(socket.SHUT_RDWR)
    socket.close()

服务器:

conn, address = socket.accept()
try:
    conn.send(message)
except:
    print "-1"

但是当我第一次运行此代码时,我通过键盘中断关闭客户端,服务器将不会在屏幕上打印-1 . 当我再次尝试时,服务器将捕获异常并打印-1 .

我想知道我的代码是否有问题 . 为什么服务器第一次检测不到断开连接?

谢谢 .