如何在python3.6中检测套接字/连接突然关闭

2024-04-15 23:49:02 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在Python3.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()

如果客户机正常断开连接,则它将正确关闭连接。如何检查客户端是否突然断开连接?你知道吗


Tags: true客户端datavalueassocketconntemp
1条回答
网友
1楼 · 发布于 2024-04-15 23:49:02

您可以在开始时尝试向客户机发送一个数据包,通过它可以查看您是否连接到客户机

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

在接收线上你可以做:

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

相关问题 更多 >