script_websocket.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. # This Python file uses the following encoding: utf-8
  2. # @author runhey
  3. # github https://github.com/runhey
  4. from typing import Iterable
  5. from fastapi import WebSocket, WebSocketDisconnect
  6. from starlette.websockets import WebSocketState
  7. class ScriptWSManager:
  8. def __init__(self):
  9. self.active_connections: list[WebSocket] = []
  10. async def connect(self, ws: WebSocket):
  11. # 等待连接
  12. await ws.accept()
  13. if ws not in self.active_connections:
  14. self.active_connections.append(ws)
  15. async def disconnect(self, ws: WebSocket):
  16. # 关闭时移除 ws 对象,重复调用也应安全
  17. if ws in self.active_connections:
  18. self.active_connections.remove(ws)
  19. if ws.client_state == WebSocketState.DISCONNECTED:
  20. return
  21. try:
  22. # 给前端发送最后一次关闭信号
  23. await ws.close()
  24. except (RuntimeError, WebSocketDisconnect):
  25. return
  26. except Exception:
  27. return
  28. async def send_text(self, ws: WebSocket, message: str) -> bool:
  29. return await self._send(ws, ws.send_text, message)
  30. async def send_json(self, ws: WebSocket, data: dict) -> bool:
  31. return await self._send(ws, ws.send_json, data)
  32. async def broadcast(self, message: str):
  33. # 广播消息
  34. await self._broadcast(self.active_connections, lambda connection: connection.send_text(message))
  35. async def broadcast_state(self, data: dict):
  36. # 广播自身的状态
  37. await self._broadcast(self.active_connections, lambda connection: connection.send_json(data))
  38. async def broadcast_log(self, log: str):
  39. # 广播日志
  40. await self._broadcast(self.active_connections, lambda connection: connection.send_text(log))
  41. async def _send(self, ws: WebSocket, sender, payload) -> bool:
  42. if ws.client_state == WebSocketState.DISCONNECTED:
  43. await self.disconnect(ws)
  44. return False
  45. try:
  46. await sender(payload)
  47. return True
  48. except (RuntimeError, WebSocketDisconnect):
  49. await self.disconnect(ws)
  50. return False
  51. except Exception:
  52. await self.disconnect(ws)
  53. return False
  54. async def _broadcast(self, connections: Iterable[WebSocket], sender_factory) -> None:
  55. dead_connections: list[WebSocket] = []
  56. for connection in list(connections):
  57. if connection.client_state == WebSocketState.DISCONNECTED:
  58. dead_connections.append(connection)
  59. continue
  60. try:
  61. await sender_factory(connection)
  62. except (RuntimeError, WebSocketDisconnect):
  63. dead_connections.append(connection)
  64. except Exception:
  65. dead_connections.append(connection)
  66. for connection in dead_connections:
  67. await self.disconnect(connection)