websocket_server.py 1.35 KB
Newer Older
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
55
56
57
58
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.

"""
A WebSocket server runs on random port, accepting one single client.

It prints each message received from client to stdout,
and send each line read from stdin to the client.
"""

import asyncio
import sys

import aioconsole
import websockets

sys.stdin.reconfigure(encoding='utf_8')
sys.stdout.reconfigure(encoding='utf_8')
sys.stderr.reconfigure(encoding='utf_8')

_ws = None

async def main():
    await asyncio.gather(
        ws_server(),
        read_stdin()
    )

async def read_stdin():
    async_stdin, _ = await aioconsole.get_standard_streams()
    async for line in async_stdin:
        line = line.decode().strip()
        _debug(f'read from stdin: {line}')
        if line == '_close_':
            exit()
        await _ws.send(line)

async def ws_server():
    async with websockets.serve(on_connect, 'localhost', 0) as server:
        port = server.sockets[0].getsockname()[1]
        print(port, flush=True)
        _debug(f'port: {port}')
        await asyncio.Future()

async def on_connect(ws):
    global _ws
    _debug('connected')
    _ws = ws
    async for msg in ws:
        _debug(f'received from websocket: {msg}')
        print(msg, flush=True)

def _debug(msg):
    #sys.stderr.write(f'[server-debug] {msg}\n')
    pass

if __name__ == '__main__':
    asyncio.run(main())