script_websocket.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  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. def disconnect(self, ws: WebSocket):
  13. # 关闭时 移除ws对象
  14. self.active_connections.remove(ws)
  15. async def broadcast(self, message: str):
  16. # 广播消息
  17. for connection in self.active_connections:
  18. await connection.send_text(message)
  19. async def broadcast_state(self, data: dict):
  20. # 广播自身的状态
  21. for connection in self.active_connections:
  22. await connection.send_json(data)
  23. async def broadcast_log(self, log: str):
  24. # 广播日志
  25. for connection in self.active_connections:
  26. try:
  27. await connection.send_text(log)
  28. except RuntimeError as e:
  29. print(e)
  30. self.active_connections.remove(connection)