我正在构建一个基本的python web服务器,但我一直遇到一个问题,即它不发送任何数据(通过访问与它运行在同一台计算机上的网站的方式,我有服务器尝试访问的文件),下面是我的代码:
import socket
HOST, PORT = '', 80
def between(left,right,s):
before,_,a = s.partition(left)
a,_,after = a.partition(right)
return a
filereq = ""
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))
lines = []
print("Started!")
listen_socket.listen(1)
print("Listening")
while True:
try:
lines = []
client_connection, client_address = listen_socket.accept()
print("Connected")
request = client_connection.recv(1024)
print("Received Data!")
filereq = between("GET /", " HT", request)
print(filereq)
filereq = open(filereq)
for line in filereq:
lines.append(line)
print(lines)
sendata = ''.join(lines)
print(sendata)
http_response = """\
HTTP/1.1 200 OK
{}
""".format(sendata)
print(http_response)
client_connection.sendall(http_response)
print("Sent the Data!")
client_connection.close()
print("Connection Closed!")
except:
5+5
问题是服务器是用Python3实现的,但是代码混合了字节和字符串,这在Python2中有效,但在Python3中无效。你知道吗
这会导致between函数出错,因为正在对
bytes
对象调用partition
,但提供了str
分隔符值。你知道吗要解决此问题,请在从套接字读取时将数据从
bytes
解码到str
,然后在发送响应之前将数据编码回bytes
(socket.sendall
期望bytes
作为参数)。你知道吗另外,打印出发生的任何异常,以便可以调试它们。你知道吗
相关问题 更多 >
编程相关推荐