此文记录本人学习进步点滴,如有错误或不妥,请不吝赐教。
在使用python搭建一个简单的web server时遇到的问题,代码如下
import socket
HOST, PORT = '', 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 '+str(PORT)+'...')
while True:
client_connection, client_address = listen_socket.accept()
request = client_connection.recv(1024)
print(request)
http_resp = """\
HTTP/1.1 200 OK
Hello, World!
"""
client_connection.sendall(http_resp)
client_connection.close()
错误信息表明这是一个类型错误。在stackoverflow上寻找解决方案,发现这是在把python 2版本的代码移植到python 3版本时容易发生的错误。
在python 3中,bytes strings 和 unicode strings是两个不同的类型。我们知道,在网络通信的socket中,使用的是字节流,即bytes strings,而程序中的http_resp是unicode string,所以会发生TypeError,因为socket使用的是字节流buffer。
幸而,python提供了bytes strings和unicode strings之间进行转换的机制。使用unicode strings的encode()可以将其转为bytes strings;使用bytes strings的decode()可以将其转为unicode strings。
好,我们尝试一下,将原代码中的client_connection.sendall(http_resp)改为client_connection.sendall(http_resp.encode()),运行脚本,可正常运行
接着我们打开浏览器,访问localhost:8888/hello,能正常访问
我们知道,python中的bytes strings定义需在前面附上字符b,所以我们尝试另一种解决方案,修改http_resp定义为
http_response = b"""\
HTTP/1.1 200 OK
Hello, World!
"""
同样能正常运行脚本和访问localhost:8888/hello,所以可知问题确实是由bytes strings和unicode strings引起的。