TypeError: can only concatenate str (not "bytes") to str In Socket Module

TypeError: can only concatenate str (not "bytes") to str In Socket Module

我目前正在做一个名为 Door(On-The)Floor 或 DoorFloor 的项目
当我 运行 我得到这个:

Server Running on http://192.168.56.1:8080  
127.0.0.1 Requested GET / HTTP/1.1  
Sent 127.0.0.1 File: GET / HTTP/1.1  
127.0.0.1 Requested GET /logo-500x500 HTTP/1.1  
Traceback (most recent call last):  
 File "G:\DoorFloor\main.py", line 43, in <module>  
   CreateServer(port=8080 )  
 File "G:\DoorFloor\main.py", line 31, in CreateServer  
      data += open("assets/logo-500x500.jpg", "rb").read()  
    TypeError: can only concatenate str (not "bytes") to str  

是的,我 运行 使用“rb”打开,但我不知道如何解决这个问题
代码在github:
https://github.com/penguinpolarDOTnet/DoorFloor
只有 index.html 页面会加载 我没有在 main.py 上做太多,它是 self

考虑这段代码:

data =  "HTTP/1.1 200 OK\r\n"
if rd.split("/")[1] == " HTTP":
    data += "Content-Type: text/html\r\n\r\n"
    data += open("index.html", "r").read()
    data += "\r\n\r\n"
if rd.split("/")[1] == "logo-500x500 HTTP":
    data += "Content-Type: image/jpeg\r\n\r\n"
    data += open("assets/logo-500x500.jpg", "rb").read()
    data += "\r\n\r\n"
clientsocket.sendall(data.encode())

data 用字符串初始化,然后后续行用字符串和字节扩展它。因此 TypeError: can only concatenate str (not "bytes") to str。适用于这种小情况的一种解决方案是将所有字符串都视为字节:

data = bytearray(b"HTTP/1.1 200 OK\r\n")
if rd.split("/")[1] == " HTTP":
    data += b"Content-Type: text/html\r\n\r\n"
    data += open("index.html", "rb").read()
    data += b"\r\n\r\n"
# etc.

请注意,您无法在文本模式下阅读 jpg。