[Python] This HTTP server I written mostly works, but has an issue with mobile Chrome

Discussão em 'Python' iniciado por Stack, Abril 10, 2025.

  1. Stack

    Stack Membro Participativo

    This web server runs fine for simple web-serving tasks, but it gives me a "broken pipe" error when sending large files to devices with mobile Chrome specifically. The only thing different with mobile Chrome is that it does not send a "Keep-alive" in the header.

    I did not try anything. I expected to get a successful connection just like any other browser.

    My code


    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind(('0.0.0.0', 80))
    s.listen()
    while True:
    conn, addr = s.accept()
    with conn:
    req = conn.recv(1024).decode("utf-8")
    print(req)
    req = req.split(" ")
    if(req[0] == "GET"):
    try:
    fname = req[1]
    if(fname == "/"):
    fname = "index.html"
    else:
    fname = os.path.relpath(os.path.abspath("." + fname))
    with open(fname, "rb") as f:
    mtype = mimetypes.guess_type(fname)[0]
    conn.sendall(f"HTTP/1.1 200 OK\nContent-Type: {mtype}\n\n".encode('utf-8') + f.read())
    except:
    conn.sendall(b"HTTP/1.1 404 Not Found")
    else:
    print("LOL No!")
    conn.sendall(b"HTTP/1.1 400 Bad Request\n\n")

    Continue reading...

Compartilhe esta Página