script_websocket.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. # This Python file uses the following encoding: utf-8
  2. # @author runhey
  3. # github https://github.com/runhey
  4. from fastapi import FastAPI, WebSocket, WebSocketDisconnect
  5. class ScriptWSManager:
  6. def __init__(self):
  7. self.active_connections: list[WebSocket] = []
  8. async def connect(self, ws: WebSocket):
  9. # 等待连接
  10. await ws.accept()
  11. self.active_connections.append(ws)
  12. async def disconnect(self, ws: WebSocket):
  13. # 关闭时 移除ws对象
  14. self.active_connections.remove(ws)
  15. try:
  16. # 给前端发送最后一次关闭信号
  17. await ws.close()
  18. except RuntimeError as e:
  19. print(e)
  20. async def broadcast(self, message: str):
  21. # 广播消息
  22. for connection in self.active_connections:
  23. try:
  24. await connection.send_text(message)
  25. except RuntimeError:
  26. await self.disconnect(connection)
  27. async def broadcast_state(self, data: dict):
  28. # 广播自身的状态
  29. for connection in self.active_connections:
  30. try:
  31. await connection.send_json(data)
  32. except RuntimeError:
  33. await self.disconnect(connection)
  34. async def broadcast_log(self, log: str):
  35. # 广播日志
  36. for connection in self.active_connections:
  37. try:
  38. await connection.send_text(log)
  39. except RuntimeError:
  40. await self.disconnect(connection)