Python套接字服务器TypeError:需要类似bites的对象,而不是“str”

2024-04-26 13:47:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我找到了这个线索:Python sockets error TypeError: a bytes-like object is required, not 'str' with send function

但我的问题是-当我在HTML字符串前添加b或对其进行编码时,在浏览器上打开网站时不再出现错误-但我也不再看到该网站!我只是得到一个空白的白色屏幕,有时一个错误,说它不能加载网站。 为什么会这样?我该如何预防?它在micropython中运行良好,但在我的计算机上使用的python3中却不行。你知道吗

这是我使用的代码:

    # Complete project details at https://RandomNerdTutorials.com
import socket
html = b"""<html><head><title>TEST</title>TEST</head></html>"""

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 80))
s.listen()

while True:
    print(s)
    conn, addr = s.accept()
    print('Got a connection from %s' % str(addr))
    response = html
    conn.send(html)
    conn.close()

Tags: testsendtitle网站html错误errorsocket