文件如下:
import socket
HOST, PORT = '127.0.0.1', 8888
listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
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)
print (request.decode('utf-8'))
http_response = """
HTTP/1.1 200 OK
Hello, World!
""".encode("utf-8")
client_connection.sendall(http_response)
client_connection.close()
其中的 print (request.decode('utf-8'))
不加decode()还能运行,一转码不管decode()括号里面写任何东西或者空着就会报错。。
错误如下所示:
websercer1.py文件我确定是utf-8编码格式的,真心不知道这是什么回事了。。
哪位知道麻烦告知,拜谢。。。
decode is decoding.
It has nothing to do with the encoding of the websercer1.py file.
request.decode('encoding') #refers to what encoding you use to decode the request...
Your error may have been encoded in UTF-8
Although you are sure that it is UTF-8 encoding, it is recommended that you save it to a txt file first and take a look.
A stupid method I often use to crawl data is to write things into txt without thinking to see what is inside, like this Better debug
If the utf-8 format of codecs cannot be saved as txt, then your content should not be utf-8
Your encoding is originally UTF-8, so there is no need to encode or decode. That encode is redundant, (and you also wrote it wrong, you need to decode first, and then encode, so it is redundant)
http_response = """HTTP/1.1 200 OK Hello, World!""".decode('utf- 8').encode("utf-8")
It didn’t work in the end. There may be something wrong with the socket code. Please check again