我在玩一个套接字服务器,该服务器仅向连接的客户端发送消息。消息来自另一个进程。每5秒钟,每分钟或几小时就有一条新消息。
服务器保留一个已连接客户端的池。每个消息将发送给所有客户端。
现在,我正试图让服务器清理已断开连接的客户端。我认为他尝试向断开连接的客户端发送消息后,服务器将立即获得ConnectionAbortedError。 但是似乎第一条消息并没有引发此错误。仅当他尝试使用其他消息(第三条消息)时,才会引发错误。
错误不应该在第二条消息之后引发吗?
try:
# Send message to a connected client
res = connection.sendall(bytes("FIRST MESSAGE", encoding="utf8"))
print("First message succesfully send.")
print(res)
# Client has received the message and closes the connection.
time.sleep(10)
# Server sends out a new message to the disconnected client.
res = connection.sendall(bytes("SECOND MESSAGE", encoding="utf8"))
print("Second message succesfully send.")
print(res)
time.sleep(10)
# If no error, server sends out a new message to disconnected client.
res = connection.sendall(bytes("THIRD MESSAGE", encoding="utf8"))
print("Third message succesfully send.")
print(res)
except ConnectionAbortedError:
print('Connection aborted!')
结果:
First message succesfully send.
None
Second message succesfully send.
None
Connection aborted!
我将“睡眠”放在消息之间,因为消息之间始终会存在很长时间。