#!/usr/bin/env python3 import asyncio import sys from aiohttp import web from websockets.asyncio.server import broadcast, serve from websockets.exceptions import ConnectionClosed connected = set() async def index(request): data = await request.post() try: broadcast(connected, data["code"]) except KeyError: pass return web.Response() async def handle(ws): connected.add(ws) print("connected", file=sys.stderr) try: async for message in ws: pass except ConnectionClosed: pass finally: connected.remove(ws) print("disconnected", file=sys.stderr) async def main(): app = web.Application() app.add_routes([web.post("/", index)]) runner = web.AppRunner(app) await runner.setup() site = web.TCPSite(runner, "localhost", 8000) await site.start() try: async with serve(handle, "localhost", 8765) as server: await server.serve_forever() except asyncio.CancelledError: print(file=sys.stderr) print("bye", file=sys.stderr) await runner.cleanup() asyncio.run(main())