blob: cca337501ed53d5219567545dd9fe5755439b616 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
#!/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())
|