| | from fastapi import FastAPI, WebSocket |
| | import asyncio |
| | import websockets |
| |
|
| | app = FastAPI() |
| |
|
| | |
| | TARGET_WSS_URL = "wss://speech.platform.bing.com" |
| |
|
| | @app.websocket("/ws") |
| | async def websocket_endpoint(websocket: WebSocket): |
| | await websocket.accept() |
| | |
| | |
| | async with websockets.connect(TARGET_WSS_URL) as target_websocket: |
| | |
| | client_to_server = asyncio.create_task(forward_messages(websocket, target_websocket)) |
| | server_to_client = asyncio.create_task(forward_messages(target_websocket, websocket)) |
| | |
| | |
| | await asyncio.gather(client_to_server, server_to_client) |
| |
|
| | async def forward_messages(source: WebSocket, destination: WebSocket): |
| | try: |
| | while True: |
| | message = await source.receive_text() |
| | await destination.send_text(message) |
| | except websockets.exceptions.ConnectionClosed: |
| | pass |
| |
|
| | if __name__ == "__main__": |
| | import uvicorn |
| | uvicorn.run(app, host="0.0.0.0", port=8000) |