Debian Codegraph @

experiments/compression/server.py

raw
1 #!/usr/bin/env python
2
3 import asyncio
4 import os
5 import signal
6 import statistics
7 import tracemalloc
8
9 from websockets.asyncio.server import serve
10 from websockets.extensions.permessage_deflate import ServerPerMessageDeflateFactory
11
12
13 CLIENTS = 20
14 INTERVAL = 1 / 10 # seconds
15
16 WB, ML = 12, 5
17
18 MEM_SIZE = []
19
20
21 async def handler(ws):
22 msg = await ws.recv()
23 await ws.send(msg)
24
25 msg = await ws.recv()
26 await ws.send(msg)
27
28 MEM_SIZE.append(tracemalloc.get_traced_memory()[0])
29 tracemalloc.stop()
30
31 tracemalloc.start()
32
33 # Hold connection open until the end of the test.
34 await asyncio.sleep(CLIENTS * INTERVAL)
35
36
37 async def server():
38 async with serve(
39 handler,
40 "localhost",
41 8765,
42 extensions=[
43 ServerPerMessageDeflateFactory(
44 server_max_window_bits=WB,
45 client_max_window_bits=WB,
46 compress_settings={"memLevel": ML},
47 )
48 ],
49 ) as server:
50 print("Stop the server with:")
51 print(f"kill -TERM {os.getpid()}")
52 print()
53 loop = asyncio.get_running_loop()
54 loop.add_signal_handler(signal.SIGTERM, server.close)
55
56 tracemalloc.start()
57 await server.wait_closed()
58
59
60 asyncio.run(server())
61
62
63 # First connection incurs non-representative setup costs.
64 del MEM_SIZE[0]
65
66 print(f"µ = {statistics.mean(MEM_SIZE) / 1024:.1f} KiB")
67 print(f"σ = {statistics.stdev(MEM_SIZE) / 1024:.1f} KiB")