好吧,首先我想指出不能使用网络库。我尝试做的目的是了解如何使用字符串操作/转换来提供 http 1.1 标头和数据。在这种情况下,我尝试使用 url 提供 .jpg 文件:
http://127.0.0.1:8080/01.jpg
我的服务器已经收到了 GET 请求,我的问题似乎来自文件 i/o 或我向客户端发送数据的方式。我承认我是 python 和 HTTP 的新手,所以对我要温柔;)。这是在 ubuntu 14.04 上的 python 3.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'>
我从多个来源看到了其他看起来不像这样的二进制值。据我了解,数据需要是二进制的,以便服务器通过套接字将其发送到客户端。如果这不正确,我的文件 i/o 中缺少什么?如果这是正确的,我错过了哪一步可以让我使用 sendall() 发送数据?
鉴于上述问题,file_data 如何影响 sendall()?
client_sock.sendall(file_data) TypeError: '_io.BufferedReader' does not support the buffer interface
通过阅读 python3 文档第 18.1 节,我看到 sendall() 的参数应该是字节。file_data 是否需要像标头一样使用 bytes(xxx, 'idk what encoding') 进行编码?使用'ascii'根本不起作用。
- 您是否建议我使用字节数组来存储 http 响应标头和文件数据,以便两者都可以在一个 sendall() 中发送?或者这不是必需的吗?
浏览器(Firefox)上的输出:
The image "http://127.0.0.1:8080/01.jpg" cannot be displayed because it contains erros.
谢谢你们。如果需要更多信息,请告诉我。