Http headers 以二进制形式读取http服务器python 3.4的图像

Http headers 以二进制形式读取http服务器python 3.4的图像,http-headers,binary-data,python-3.4,httpserver,python-sockets,Http Headers,Binary Data,Python 3.4,Httpserver,Python Sockets,好的,首先我想指出,没有网络库可以使用。我尝试做的目的是了解如何使用字符串操作/转换为HTTP1.1头和数据提供服务。在本例中,我尝试使用以下url为.jpg文件提供服务: http://127.0.0.1:8080/01.jpg 我的服务器已经收到GET请求,我的问题似乎来自文件i/o或我向客户端发送数据的方式。我承认我对python和HTTP还不熟悉,所以请对我温柔一点;)。这是在ubuntu 14.04上的Python3.4上完成的 相关代码: file_data = open(fil

好的,首先我想指出,没有网络库可以使用。我尝试做的目的是了解如何使用字符串操作/转换为HTTP1.1头和数据提供服务。在本例中,我尝试使用以下url为.jpg文件提供服务:

http://127.0.0.1:8080/01.jpg 
我的服务器已经收到GET请求,我的问题似乎来自文件i/o或我向客户端发送数据的方式。我承认我对python和HTTP还不熟悉,所以请对我温柔一点;)。这是在ubuntu 14.04上的Python3.4上完成的

相关代码:

file_data = open(file_directory,'rb')
...
# Other code in between exists
...

# res is a unicode string that contains the headers for the http response

header = bytes(res, 'ascii')

#   Send Response header
client_sock.sendall(header)

#   Send file data
client_sock.sendall(file_data)
问题:

  • .jpg文件的二进制读取是否应为:

    <_io.BufferedReader name='/home/website/html/01.jpg'>
    
  • 通过阅读python3文档第18.1节,我看到sendall()的参数应该是字节。文件_数据是否需要使用字节(xxx,'idk what encoding')作为头进行编码?使用“ascii”根本不起作用

  • 您是否建议我使用字节数组来存储http响应头和文件数据,以便两者都可以在一个sendall()中发送?或者这不是必须的
  • 浏览器(Firefox)上的输出:


    谢谢大家。如果需要更多信息,请告诉我

    好了,伙计们,看来我的问题很简单。解决方案是使用下面的代码发送所有数据

    # Replace code for data send all with line below:
    client_sock.sendall(filedata.read())
    
    # This only creates a file type object that we can read. 
    # Not responsible for an actual read!
    file_data = open(file_directory,'rb')
    
    x、 read()实际上会根据open定义的方式从文件对象x中读取

    我现在意识到文件\u数据不是读取数据,而是文件对象

    The image "http://127.0.0.1:8080/01.jpg" cannot be displayed because it contains erros.
    
    # Replace code for data send all with line below:
    client_sock.sendall(filedata.read())
    
    # This only creates a file type object that we can read. 
    # Not responsible for an actual read!
    file_data = open(file_directory,'rb')