'ConnectionResetError with BaseHTTPServer download file Python

Problem:

I need to download large files (4MB and 6MB) using HTTP in Python. When I use smaller file sizes it goes ok without problems; but, when I use the sizes above, it breaks. This is the error:

ConnectionResetError: [WinError 10054]

Command for execution:

py server.py file.type ip_address port_number

Code:

import http.server as BaseHTTPServer
import os
import shutil
import sys

FILEPATH = sys.argv[1] if sys.argv[1:] else __file__

class SimpleHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == '/' + str(FILEPATH):
            downloadFile(self)
        else:
            endpointNotSpecified(self)

def downloadFile(self):
    with open(FILEPATH, 'rb') as file:
        self.send_response(200)
        self.send_header("Content-Type", 'application/octet-stream')
        self.send_header("Content-Disposition", 'attachment; filename="{}"'.format(os.path.basename(FILEPATH)))

        fileSystem = os.fstat(file.fileno())
        
        self.send_header("Content-Length", str(fileSystem.st_size))
        self.end_headers()

        shutil.copyfileobj(file, self.wfile)

def endpointNotSpecified(self):
    self.send_response(200)
    self.send_header("Content-type", "text/html")
    self.end_headers()

    html = f"<html><head></head><body><h1>USE THE SPECIFIED FILEPATH IN THE ENDPOINT TO DOWNLOAD THE FILE</h1></body></html>"

    self.wfile.write(bytes(html, "utf8"))

def verifyServerPort():
    if sys.argv[3:]:
        port = int(sys.argv[3])
    else:
        port = 8000

    return port

def runServer(port, HandlerClass=SimpleHTTPRequestHandler, ServerClass=BaseHTTPServer.HTTPServer, protocol="HTTP/1.0"):
    serverAddress = (str(sys.argv[2]), port)

    HandlerClass.protocol_version = protocol
    httpd = ServerClass(serverAddress, HandlerClass)

    socketAddress = httpd.socket.getsockname()
    print("Serving HTTP on localhost: {0[0]}:{0[1]}/{1}".format(socketAddress, FILEPATH))

    httpd.serve_forever()

if __name__ == '__main__':
    port = verifyServerPort()
    
    runServer(port)


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source