简体   繁体   English

收到错误消息:[Errno 10053]尝试在http响应中发送文件时

[英]Getting error: [Errno 10053] while trying to send a file in http response

Am trying to send a big file in http response by writing into wfile variable of BaseHTTPRequestHandler in Python, when I am trying to do that I am ending with the below exception in my Python code always. 我试图通过写入Python中的BaseHTTPRequestHandler wfile变量来发送http响应中的大文件,而当我试图这样做时,我总是在Python代码中以以下异常结尾。

error: [Errno 10053] An established connection was aborted by the software in your machine

Can any one help me to resolve this?? 谁能帮我解决这个问题? why am getting the error? 为什么会出现错误? If the way am sending large file in HTTP response is not the good one, please suggest where I can refer. 如果在HTTP响应中发送大文件的方法不好,请提出建议。

Thanks in advance!!! 提前致谢!!!

import os
import urlparse
import BaseHTTPServer
from SocketServer import ThreadingMixIn
import urlparse

class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
    def handle(self):
        BaseHTTPServer.BaseHTTPRequestHandler.handle(self)

    def sendError(self, errorCode, errorMessage):
        self.send_response(errorCode, errorMessage)
        self.send_header("Content-type", "text/plain")
        self.send_header("Content-Length", str(len(errorMessage)))
        self.end_headers()
        self.wfile.write(errorMessage)

    def do_GET(self):
        scm, netloc, path, params, query, fragment = urlparse.urlparse(self.path, 'http')
        if path.find(".ld") > 0:
            filename = path.rpartition("/")[2]
            try:
                with open(filename, 'rb') as f:
                    self.send_response(200, "Ok")
                    self.send_header("Content-type","application/octet-stream")
                    total_size = os.path.getsize(filename)
                    self.send_header("Content-Length", total_size)
                    self.end_headers()
                    self.wfile.write(f.read())
            except IOError:
                self.sendError(404, "Not Found")

class ThreadedHTTPServer(ThreadingMixIn, BaseHTTPServer.HTTPServer):
    def __init__(self, server_address, RequestHandlerClass, bind_and_activate=True):
        BaseHTTPServer.HTTPServer.__init__(self, server_address, RequestHandlerClass, bind_and_activate)

def main():
    Handler.close_connection = 0
    Handler.protocol_version = 'HTTP/1.1'
    global httpd
    httpd = ThreadedHTTPServer(("", 8900), Handler)
    httpd.daemon_threads = True
    httpd.serve_forever()

if __name__ == "__main__":
    main()

Error Trace: 错误跟踪:

Exception happened during processing of request from ('172.24.128.21', 19418)
Traceback (most recent call last):
  File "C:\Python27\lib\SocketServer.py", line 593, in process_request_thread
    self.finish_request(request, client_address)
  File "C:\Python27\lib\SocketServer.py", line 334, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "C:\Python27\lib\SocketServer.py", line 649, in __init__
    self.handle()
  File "simple.py", line 10, in handle
    BaseHTTPServer.BaseHTTPRequestHandler.handle(self)
  File "C:\Python27\lib\BaseHTTPServer.py", line 342, in handle
    self.handle_one_request()
  File "C:\Python27\lib\BaseHTTPServer.py", line 310, in handle_one_request
    self.raw_requestline = self.rfile.readline(65537)
  File "C:\Python27\lib\socket.py", line 476, in readline
    data = self._sock.recv(self._rbufsize)
error: [Errno 10054] An existing connection was forcibly closed by the remote ho
st

OK, so I tried your code after cleaning it up a bit: 好的,所以我在清理了一点之后尝试了您的代码:

    def do_GET(self):
        _, _, path, _, _, _ = urlparse.urlparse(self.path, 'http')
        if path.find(".ld") > 0:
            filename = path.rpartition("/")[2]
            try:
                with open(filename, 'rb') as f:
                    self.send_response(200, "Ok")
                    self.send_header("Content-type", self.headers.getheader("Content-type", ""))
                    total_size = os.path.getsize(filename)
                    self.send_header("Content-Length", total_size)
                    self.end_headers()
                    self.wfile.write(f.read())
            except IOError:
                self.sendError(404, "Not Found")

I put a foo.pl file in the same folder; 我将foo.pl文件放在同一文件夹中; then, when doing curl http://localhost/foo.pl , I get a nice response with the content of the file, and no errors whatsoever. 然后,在执行curl http://localhost/foo.pl ,我得到了文件内容的良好响应,并且没有任何错误。

I must also say that it looks like you're just trying to get the file name without the path part using path.rpartition("/")[2] , but for that, you should just use os.path.basename : 我还必须说,看起来您只是在尝试使用path.rpartition("/")[2]来获取不带路径部分的文件名,但为此,您应该只使用os.path.basename

>>> os.path.basename('foo/bar/baz.pl')
'baz.pl'

Also, path.find(".ld") > 0 should probably be path.endswith(".ld") instead. 同样, path.find(".ld") > 0应该path.endswith(".ld")

EDIT: to support large files (efficiently): 编辑:支持大文件(有效):

CHUNK_SIZE = 1024 * 100  # 100kB chunks
while True:
    chunk = f.read(CHUNK_SIZE)
    if not chunk:
        break
    self.wfile.write(chunk)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 收到错误:FileNotFoundError:[Errno 2]没有这样的文件或目录:试图打开文件时 - Getting a error: FileNotFoundError: [Errno 2] No such file or directory: while trying to open a file 错误:[Errno 10053] - error: [Errno 10053] 尝试打开文件时出现错误“ [Errno 22]无效参数” - I`m getting an error “[Errno 22] Invalid argument” while trying to open the file AdbClient错误:[Errno 10053]建立的连接被中止 - AdbClient error: [Errno 10053] An established connection was aborted 为什么我在保存文件时收到 Errno 13 错误? - Why am I getting Errno 13 Error while saving the file? Python urlopen连接中止 - urlopen错误[Errno 10053] - Python urlopen connection aborted - urlopen error [Errno 10053] IOError:[Errno 22]尝试写入文件时 - IOError: [Errno 22] while trying to write file 尝试更新任何 package 时获取 Conda HTTP 错误 Windows - Getting Conda HTTP Error in Windows while trying to update any package Django。 尝试发送 email 时出现“ConnectionRefusedError: [Errno 111” - Django. Getting "ConnectionRefusedError: [Errno 111" when trying to send an email 在http响应中将图像发送到ajax响应中,获取错误imagefilefield不可序列化 - send image in http response to ajax response getting error imagefilefield is not JSON serializable
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM