tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

server.py (1483B)


      1 #!/usr/bin/env python
      2 
      3 import asyncio
      4 import os
      5 import signal
      6 import statistics
      7 import tracemalloc
      8 
      9 import websockets
     10 from websockets.extensions import permessage_deflate
     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    loop = asyncio.get_running_loop()
     39    stop = loop.create_future()
     40 
     41    # Set the stop condition when receiving SIGTERM.
     42    print("Stop the server with:")
     43    print(f"kill -TERM {os.getpid()}")
     44    print()
     45    loop.add_signal_handler(signal.SIGTERM, stop.set_result, None)
     46 
     47    async with websockets.serve(
     48        handler,
     49        "localhost",
     50        8765,
     51        extensions=[
     52            permessage_deflate.ServerPerMessageDeflateFactory(
     53                server_max_window_bits=WB,
     54                client_max_window_bits=WB,
     55                compress_settings={"memLevel": ML},
     56            )
     57        ],
     58    ):
     59        tracemalloc.start()
     60        await stop
     61 
     62 
     63 asyncio.run(server())
     64 
     65 
     66 # First connection may incur non-representative setup costs.
     67 del MEM_SIZE[0]
     68 
     69 print(f"µ = {statistics.mean(MEM_SIZE) / 1024:.1f} KiB")
     70 print(f"σ = {statistics.stdev(MEM_SIZE) / 1024:.1f} KiB")