Python读取html文件使用socket响应给浏览器http请求,内容显示不全?
最近在学习python,课后练习要求同学使用读取文件+socket 响应客户端浏览器请求。
我的静态页面index.html如下
<!DOCTYPE html><html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.container{
height: 100vh;
display: flex;
flex-direction: column;
justify-content: center;
align-content: center;
}
.container>div{
flex: 1;
text-align: center;
display: flex;
align-items: center;
justify-content: center;
}
.container>div:nth-child(odd){
background: antiquewhite;
}
.container>div:nth-child(even){
background: coral;
}
</style>
</head>
<body>
<div class="container">
<div>Python http 传输</div>
<div>http 网页渲染</div>
</div>
</body>
</html>
python读取文件并响应代码文件 http_html_response.py文件如下
from socket import *# 创建tcp套接字
s = socket()
s.bind(('0.0.0.0', 8000))
s.listen(3)
while True:
c, addr = s.accept()
print('Connect from', addr)
data = c.recv(4096)
print(data)
# http响应
# data = """HTTP/1.1 200 OK
# Content-Type:text/html
#
# <h1>Hello</h1>
#
#
# """
# 读取html文件,作为响应发送给客户端
with open('index.html', mode='rb') as html_file:
head_row=b"""HTTP/1.1 200 OK
Content-Type:text/html
"""
c.send(head_row)
while True:
data = html_file.read(1024)
if not data:
break
c.send(data)
c.close()
s.close()
为啥浏览器响应内容不完整?
如图所示:
正常应该显示如下:
以上是 Python读取html文件使用socket响应给浏览器http请求,内容显示不全? 的全部内容, 来源链接: utcz.com/p/938706.html