website/backend.py
2026-02-08 22:31:05 +01:00

34 lines
1.1 KiB
Python

import asyncio
import websockets
import aiohttp
async def proxy_handler(websocket, path):
target_url = await websocket.recv()
async with aiohttp.ClientSession() as session:
async with session.ws_connect(target_url) as target_ws:
async def forward_to_target():
async for msg in websocket:
if isinstance(msg, str):
await target_ws.send_str(msg)
else:
await target_ws.send_bytes(msg)
async def forward_to_client():
async for msg in target_ws:
if msg.type == aiohttp.WSMsgType.TEXT:
await websocket.send(msg.data)
elif msg.type == aiohttp.WSMsgType.BINARY:
await websocket.send(msg.data)
await asyncio.gather(
forward_to_target(),
forward_to_client()
)
async def main():
async with websockets.serve(proxy_handler, "localhost", 8765):
await asyncio.Future()
asyncio.run(main())