script_websocket.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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:
  19. pass
  20. async def broadcast(self, message: str):
  21. # 广播消息
  22. for connection in self.active_connections:
  23. await connection.send_text(message)
  24. async def broadcast_state(self, data: dict):
  25. # 广播自身的状态
  26. for connection in self.active_connections:
  27. await connection.send_json(data)
  28. async def broadcast_log(self, log: str):
  29. # 广播日志
  30. for connection in self.active_connections:
  31. try:
  32. await connection.send_text(log)
  33. except RuntimeError as e:
  34. print(e)
  35. self.active_connections.remove(connection)