简体   繁体   English

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

[英]Simple python 3 web server that shows image in browser

I'm trying to make a simple http server that can get accessed through a web browser as the client, only using the sockets module from python 3. I already got some understanding of how the http response works with its headers. 我正在尝试制作一个简单的http服务器,该服务器只能使用python 3中的sockets模块作为客户端通过Web浏览器进行访问。我已经对http响应如何与标头一起工作有所了解。 I actually confirmed through Chrome developer tool that the browser is able to comprehend my response, but the image fails to display (it only shows a black screen in the browser, meaning that there is a problem with the image). 我实际上通过Chrome开发者工具确认浏览器能够理解我的响应,但是图像无法显示(浏览器中仅显示黑屏,这意味着图像有问题)。 My guess is that I'm concatenating incorrectly the body of the image to the response String, or I'm encoding it incorrectly. 我的猜测是我将图像的主体错误地连接到响应字符串,或者我对其进行了错误的编码。 Here is my code: 这是我的代码:

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()

Currently using python 3.5.2 and elementary OS 0.4.1 Loki. 当前使用python 3.5.2和基本OS 0.4.1 Loki。

You have a typo in content length also could save cpu, no need for encoding since you announce a binary content with content type: 您在内容长度上有错别字也可以节省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) 
#

on a side note if you encode content, then you must announce size of encoded content ( in bytes ), not the size of source data (file). 在旁注中,如果您对内容进行编码,则必须声明已编码内容的大小(以字节为单位),而不是源数据(文件)的大小。

what you need is the exact size of bytes sent, which actually is the file size and not its utf-8 representation you have got with len(): 您需要的是发送的字节的确切大小,实际上是文件大小,而不是您使用len()获得的utf-8表示形式:

size = str(os.stat('404.jpg').st_size)

hope this helps. 希望这可以帮助。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM