FastAPI - Websockets,一个客户端多个连接

6ljaweal  于 2024-01-09  发布在  其他
关注(0)|答案(2)|浏览(373)

尝试在我的fastapi应用程序中实现websockets,然而,当我从JavaScript端连接到websocket时,它打开了4个连接,我在后端端实现了一个解决方案,检查某个客户是否连接,然而这意味着客户端无法连接到移动的上的websocket,而它在计算机上打开。

  1. class ConnectionManager:
  2. def __init__(self):
  3. self.connections: dict[int, WebSocket] = {}
  4. async def connect(self, websocket, customer_id):
  5. existing_connection = self.connections.get(customer_id)
  6. if existing_connection:
  7. await websocket.close()
  8. raise ExistingConnectionError("Existing connection for customer_id")
  9. await websocket.accept()
  10. websocket.customer_id = customer_id
  11. self.connections[customer_id] = websocket
  12. print(list(self.connections.values()))
  13. async def disconnect(self, websocket):
  14. customer_id = getattr(websocket, 'customer_id', None)
  15. if customer_id in self.connections:
  16. del self.connections[customer_id]
  17. async def broadcast(self, message):
  18. for websocket in self.connections.values():
  19. await websocket.send_json(message)
  20. async def broadcast_to_customer(self, customer_id, message):
  21. matching_connection = self.connections.get(customer_id)
  22. if matching_connection:
  23. await matching_connection.send_json(message)
  24. connection_manager = ConnectionManager()

个字符
JavaScript语言:

  1. let socket;
  2. if (!socket || socket.readyState !== WebSocket.OPEN) {
  3. socket = new WebSocket(`ws://localhost:3002/sock?customer_id=${customer_id}`);
  4. socket.onopen = () => {
  5. console.log('Connected to WebSocket server');
  6. };
  7. let i = 0;
  8. socket.onmessage = (event) => {
  9. const data = JSON.parse(event.data);
  10. console.log('Incoming data:', data);
  11. console.log('i:', i);
  12. i = i + 1;
  13. };
  14. }


后端日志:

  1. INFO: connection open
  2. INFO: ('127.0.0.1', 33366) - "WebSocket /sock?customer_id=185" 403
  3. Existing connection detected, rejecting the new connection
  4. INFO: connection rejected (403 Forbidden)
  5. INFO: connection closed
  6. INFO: ('127.0.0.1', 33368) - "WebSocket /sock?customer_id=185" 403
  7. Existing connection detected, rejecting the new connection
  8. INFO: connection rejected (403 Forbidden)
  9. INFO: connection closed
  10. INFO: ('127.0.0.1', 33384) - "WebSocket /sock?customer_id=185" 403
  11. Existing connection detected, rejecting the new connection
  12. INFO: connection rejected (403 Forbidden)
  13. INFO: connection closed


前端日志:

  1. Connected to WebSocket server
  2. Firefox cant establish a connection to the server at ws://localhost:3002/sock?customer_id=185.
  3. Firefox cant establish a connection to the server at ws://localhost:3002/sock?customer_id=185.
  4. Firefox cant establish a connection to the server at ws://localhost:3002/sock?customer_id=185.


尝试在FastAPI中实现WebSocket,为每个客户端打开多个连接而不是一个连接。

7hiiyaii

7hiiyaii1#

我认为你需要这样的东西:
在每个客户端的每个设备的后端存储连接上:

  1. class ConnectionManager:
  2. def __init__(self):
  3. self.clients: dict[int, dict[str, WebSocket]] = {}
  4. async def connect(self, websocket, customer_id, device_hash):
  5. client_connections = self.clients.get(customer_id)
  6. if client_connections:
  7. client_device_connection = client_connections.get(device_hash)
  8. if client_device_connection:
  9. await websocket.close()
  10. raise ExistingConnectionError("Existing connection for customer_id")
  11. else:
  12. self.clients[customer_id] = {}
  13. await websocket.accept()
  14. websocket.customer_id = customer_id
  15. websocket.device_hash = device_hash
  16. self.clients[customer_id][device_hash] = websocket
  17. print(list(self.clients.values()))
  18. async def disconnect(self, websocket):
  19. customer_id = getattr(websocket, 'customer_id', None)
  20. device_hash = getattr(websocket, 'device_hash', None)
  21. client_connections = self.clients.get(customer_id)
  22. if client_connections:
  23. if client_connections.get(device_hash):
  24. client_connections.pop(device_hash)
  25. async def broadcast(self, message):
  26. for client_connections in self.clients.values():
  27. for websocket in client_connections.values():
  28. await websocket.send_json(message)
  29. async def broadcast_to_customer(self, customer_id, message):
  30. client_connections = self.client.get(customer_id)
  31. if client_connections:
  32. for connection in client_connections.values():
  33. await connection.send_json(message)
  34. connection_manager = ConnectionManager()
  35. @app.websocket("/sock")
  36. async def websocket_endpoint(websocket: WebSocket, customer_id: int, device_hash: str):
  37. try:
  38. await connection_manager.connect(websocket, customer_id, device_hash)
  39. while True:
  40. data = await websocket.receive_json()
  41. except WebSocketDisconnect:
  42. await connection_manager.disconnect(websocket)
  43. except ExistingConnectionError:
  44. print("Existing connection detected, rejecting the new connection")

字符串
当您从前端连接到WebSocket时,添加额外的查询参数device_hash,该参数对于每个用户设备都应该是唯一的。您也可以在服务器端从请求头生成此device_hash(例如,您可以使用user-agent

展开查看全部
5f0d552i

5f0d552i2#

此问题可能与您如何检查前端上现有的WebSocket连接有关。
在你的JavaScript代码中,你每次都在创建一个新的WebSocket连接,而没有检查连接是否已经存在。为了确保只建立一个WebSocket连接,你应该以不同的方式处理WebSocket创建逻辑。一种方法是只在WebSocket不存在或不处于打开状态时才创建WebSocket。JavaScript代码的示例修改:

  1. let socket;
  2. // Check if the socket is undefined or not open
  3. if (!socket || socket.readyState !== WebSocket.OPEN) {
  4. // Create a new WebSocket connection
  5. socket = new WebSocket(`ws://localhost:3002/sock?customer_id=${customer_id}`);
  6. socket.onopen = () => {
  7. console.log('Connected to WebSocket server');
  8. };
  9. socket.onmessage = (event) => {
  10. const data = JSON.parse(event.data);
  11. console.log('Incoming data:', data);
  12. };
  13. socket.onclose = (event) => {
  14. console.log('WebSocket closed:', event);
  15. };
  16. }

字符串
此修改可确保仅在不存在现有连接或现有连接未处于打开状态时才创建新的WebSocket连接。
您可能希望处理onclose事件以处理WebSocket连接意外关闭的情况。

展开查看全部

相关问题