首页 > 解决方案 > 如何检测套接字/连接在 Python 3.6 中突然关闭

问题描述

如何在 Python 3.6 中检查客户端是否突然断开连接。这是我的代码,

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Socket created')

try:
    s.bind((HOST, PORT))
    print('Socket binding complete')
except socket.error as socketError:
    print('socket binding failed, ', socketError)

s.listen(1)
print('Socket listening for connection...')

conn, addr = s.accept()
conn.setblocking(0)
print('connected to ', addr[0])

try:
    while True:
        temp = conn.recv(1024)
        if not temp:
            break
        data = int.from_bytes(temp, byteorder='big', signed=True)
        print('value received,', temp)
        print('converted value = ', data)
except Exception as loopException:
    print("Exception occurred in loop, exiting...", loopException)
finally:
    conn.close()
    s.close()

如果客户端正常断开连接,这是有效的,它正在正确关闭连接。如何检查客户端是否突然断开连接?

标签: pythonsocketspython-3.6

解决方案


您可以在一开始尝试向客户端发送一个数据包,然后您可以查看您是否连接到客户端

while True:
    try:
        string = "Are you up?"
        s.send(string.encode())
    except:
        print("Can't seem to be connected with the client")
        # here you can process the expection
    # rest of the code

在您的情况下,您已经在使用非阻塞套接字conn.setblocking(0),因此即使客户端结束会话并且您没有收到任何数据temp,变量也不会包含任何内容,并且您将从循环中中断(如果客户端是客户端在每个循环中发送数据)

或者您也可以为客户端的响应设置超时

s.settimeout(30) # wait for the response of the client 30 seconds max

在 recv 行中,您可以执行以下操作:

try:
    temp = conn.recv(1024)
except socket.timeout:
    print('Client is not sending anything')

推荐阅读