python - 在浏览器中显示图像的简单 python 3 Web 服务器

标签 python sockets http server

我正在尝试制作一个简单的http服务器,它可以作为客户端通过网络浏览器进行访问,仅使用python 3中的套接字模块。我已经对http响应如何与其 header 一起工作有了一些了解。我实际上通过Chrome开发者工具确认浏览器能够理解我的响应,但图像无法显示(它只在浏览器中显示黑屏,这意味着图像有问题)。我的猜测是我错误地将图像主体连接到响应字符串,或者我错误地对其进行了编码。这是我的代码:

import socket
import base64
import os

HOST_N = socket.gethostname()
HOST, PORT = socket.gethostbyname(HOST_N), 10080

print(HOST)

listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP) 
listen_socket.bind((HOST, PORT))
listen_socket.listen(1)
print('Serving HTTP on port %s ...' % PORT)
while True:
    client_connection, client_address = listen_socket.accept()
    request = client_connection.recv(1024)
    option = request.decode().split(' ')
    print(request)

    if option[1]:

        if option[1]=='/success.jpg':

            with open("success.jpg", "r+b") as image_file:
                encoded_string = base64.b64encode(image_file.read())
                size = str(os.path.getsize("success.jpg"))

                HTTP_RESPONSE = "HTTP/1.1 200 OK\r\n" + "Connection: close\r\n" + "Content-Type: image/jpg\r\n" + "Content-Lenght: "+ size + "\r\n\r\n" + str(encoded_string)

                print(HTTP_RESPONSE)
                client_connection.sendall(HTTP_RESPONSE.encode('ASCII'))



        else:

            with open("404.jpg", "r+b") as image_file:
                encoded_string = base64.b64encode(image_file.read())
                size = str(os.path.getsize("404.jpg"))

                HTTP_RESPONSE = "HTTP/1.1 200 OK\n" + "Connection: close\n" + "Content-Type: image/jpg\n" + "Content-Lenght: "+ size + "\n\n" + str(encoded_string)

                client_connection.sendto(HTTP_RESPONSE.encode('ASCII'), (HOST, PORT))

    else:
        pass    

    client_connection.close()

当前使用 python 3.5.2 和elementary OS 0.4.1 Loki。

最佳答案

您的内容长度有拼写错误 还可以节省 CPU,无需编码,因为您声明了内容类型为二进制内容:

#
data = image_file.read()
HTTP_RESPONSE = b'\r\n'.join([
    b"HTTP/1.1 200 OK",
    b"Connection: close",
    b"Content-Type: image/jpg",
    bytes("Content-Length: %s" % len(data),'utf-8'),
    b'', data 
] )
client_connection.sendall(HTTP_RESPONSE) 
#

附带说明,如果您对内容进行编码,则必须声明编码内容的大小(以字节为单位),而不是源数据(文件)的大小。

关于python - 在浏览器中显示图像的简单 python 3 Web 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49573531/

相关文章:

python - 由于IndentationError : unexpected indent Python而无法写新行

c - 如何从同一个套接字发送和接收?

python - Scrapy - 如何停止元刷新重定向?

c# - 如何在异步多线程爬虫中锁定回调类?

python - 网站需要在 python 中更新

python - Qt WebEngine 似乎已初始化

python - 通过 python3 子进程发送管道命令

Python SocketServer 从服务器发送消息

php - PHP套接字连接

javascript - 如何每 N 秒安排一次 ajax 调用?