Spaces:
Running
Running
import asyncio | |
import websockets | |
async def handle_user_client(websocket, path): | |
external_uri = 'wss://ramesh-vani-wspython.hf.space' | |
async with websockets.connect(external_uri) as external_ws: | |
async def forward_user_to_external(): | |
async for user_message in websocket: | |
await external_ws.send(user_message) | |
async def forward_external_to_user(): | |
async for external_message in external_ws: | |
print(f"Received from external server: {external_message}") | |
await websocket.send(external_message) | |
# Start two tasks to handle message forwarding in both directions | |
await asyncio.gather( | |
forward_user_to_external(), | |
forward_external_to_user(), | |
) | |
# Set up WebSocket server for user | |
user_server = websockets.serve(handle_user_client, "0.0.0.0", 7860) | |
# Start the server and run the event loop | |
asyncio.get_event_loop().run_until_complete(user_server) | |
asyncio.get_event_loop().run_forever() | |