| | |
| | | asyncio.create_task(forward_to_service()), |
| | | asyncio.create_task(forward_to_client()) |
| | | ] |
| | | done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED) |
| | | |
| | | # 取消未完成的任务 |
| | | for task in pending: |
| | | task.cancel() |
| | | try: |
| | | await task |
| | | except asyncio.CancelledError: |
| | | pass |
| | | |
| | | except WebSocketDisconnect: |
| | | print(f"Client {chat_id} disconnected") |
| | | except WebSocketDisconnect as e: |
| | | print(f"WebSocket connection closed with code {e.code}: {e.reason}") |
| | | await websocket.close() |
| | | await service_websocket.close() |
| | | except Exception as e: |
| | | print(f"Exception occurred: {e}") |
| | | finally: |
| | | print("Cleaning up resources") |
| | | # 取消所有任务 |
| | | for task in tasks: |
| | | if not task.done(): |
| | | task.cancel() |
| | | try: |
| | | await task |
| | | except asyncio.CancelledError: |
| | | pass |
| | | |
| | | |
| | | @router.get("/variables/list", response_model=ResponseList) |