#!/usr/bin/env python3 """ WebSocket-to-IRC bridge for gamja anonymous web client. Each WebSocket connection gets its own TCP connection to ngircd. Listens on 127.0.0.1:7778, forwards to 127.0.0.1:6667. """ import asyncio import websockets WS_HOST = "127.0.0.1" WS_PORT = 7778 IRC_HOST = "127.0.0.1" IRC_PORT = 6667 async def bridge(ws): try: reader, writer = await asyncio.open_connection(IRC_HOST, IRC_PORT) except OSError: await ws.close() return async def ws_to_irc(): try: async for msg in ws: data = msg if isinstance(msg, bytes) else msg.encode() writer.write(data) await writer.drain() except Exception: pass finally: writer.close() async def irc_to_ws(): try: while True: data = await reader.read(4096) if not data: break await ws.send(data) except Exception: pass finally: await ws.close() await asyncio.gather(ws_to_irc(), irc_to_ws()) async def main(): async with websockets.serve(bridge, WS_HOST, WS_PORT): await asyncio.Future() asyncio.run(main())