关于websocket断开连接
connection handler failed
Traceback (most recent call last):
File "/usr/local/python3/lib/python3.9/site-packages/websockets/legacy/server.py", line 240, in handler
await self.ws_handler(self)
File "/usr/local/python3/lib/python3.9/site-packages/websockets/legacy/server.py", line 1186, in _ws_handler
return await cast(
File "/home/model/model5_new/Main.py", line 42, in handle_client
capture = await receive_message(websocket, capture)
File "/home/model/model5_new/Main.py", line 25, in receive_message
return VideoCapture(await websocket.recv())
File "/usr/local/python3/lib/python3.9/site-packages/websockets/legacy/protocol.py", line 568, in recv
await self.ensure_open()
File "/usr/local/python3/lib/python3.9/site-packages/websockets/legacy/protocol.py", line 944, in ensure_open
raise self.connection_closed_exc()
websockets.exceptions.ConnectionClosedOK: received 1005 (no status code [internal]); then sent 1005 (no status code [internal])
之前项目中出现过报错如上。自己测试中没有出现问题,但是实际运行的时候会报错。
原因是项目中有一段代码:
try:
message = await asyncio.wait_for(websocket.recv(), timeout=0.1) # 设置超时时间为5秒
await asyncio.sleep(0)
print("接收到了:",message)
if message is None:
return capture
elif message == "over":
return VideoCapture(await websocket.recv())
else:
return VideoCapture(message)
except asyncio.TimeoutError:
return capture
代码逻辑是,接受客户端发来的消息,如果接收到视频链接,则返回一个摄像头调用url。如果接收到了“over”,则代表关闭摄像头,此时等待客户端下次发送的信息。
重点在于VideoCapture(await websocket.recv())。
用apipost测试的时候是直接发送了“over”,此时代码会停下,等待客户端下次发送一个正常的视频链接。
而实际运行的时候,在发送了“over”后,摄像头关闭,会直接把websocket连接断掉,那么此时await websocket.recv()这样是非法的。所以报错。
所以最后还是改成了,不在这里接受消息并判断了。单纯用于接受消息
async def receive_message(websocket):
try:
message = await asyncio.wait_for(websocket.recv(), timeout=0.1) # 设置超时时间为5秒
return message
except asyncio.TimeoutError:
return None
主函数中:
try:
……
message = await receive_message(websocket)
await asyncio.sleep(0)
……
except:
print("断开连接")

浙公网安备 33010602011771号