Created
July 24, 2021 20:14
-
-
Save NicolaiSoeborg/51a6d8e36d41bbb27179ac9e7166772f to your computer and use it in GitHub Desktop.
Slow
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from time import time | |
from functools import partial | |
import random | |
import trio # python3 -m pip install --upgrade trio | |
FTP_RESPONSE = "\r\n".join([ | |
"220 ProFTPD 1.3.1 Server (ProFTPD)", | |
"220 " + "".join(random.choice('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') for _ in range(1001)), | |
"331 Password required" | |
]) | |
HTTP_RESPONSE = "\r\n".join([ | |
"HTTP/1.1 200 OK", | |
"connection: close", | |
"server: gws", | |
"content-type: text/html", | |
"content-length: 2001" | |
"", "", | |
"".join(random.choice('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') for _ in range(2001)) | |
]) | |
def e(extra): | |
return extra + random.random() | |
t0 = time() | |
def log(msg): | |
print(f"[{int(time()-t0)}] {msg}") | |
async def slow_read(stream): | |
while b"" != await stream.receive_some(max_bytes=1): | |
await trio.sleep(e(0.2)) | |
async def slow_write(content, stream): | |
for c in content: | |
await trio.sleep(e(0.2)) | |
await stream.send_all(c.encode()) | |
async def handler(content, stream): | |
log(f"Got conn: {stream.socket}") | |
async with trio.open_nursery() as nursery: | |
nursery.start_soon(slow_read, stream) | |
await trio.sleep(e(0.1)) | |
nursery.start_soon(partial(slow_write, content), stream) | |
log(f"End conn: {stream}") | |
async def run_on_port(content, port): | |
while True: | |
try: | |
f = partial(handler, content) | |
await trio.serve_tcp(f, port) | |
except Exception as ex: | |
log(f"Server dead on port {port}. Exception: {ex}") | |
async def main(): | |
async with trio.open_nursery() as nursery: | |
nursery.start_soon(run_on_port, FTP_RESPONSE, 21) | |
nursery.start_soon(run_on_port, HTTP_RESPONSE, 80) | |
nursery.start_soon(run_on_port, HTTP_RESPONSE, 81) | |
nursery.start_soon(run_on_port, HTTP_RESPONSE, 8080) | |
if __name__ == '__main__': | |
trio.run(main) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment