如何解决简单的Python TCP服务器不发送整个网页
我是Compsci的初学者,我正在尝试用python编写一个简单的服务器,该服务器采用存储在同一目录中的.HTML页面,并使用TCP连接将其发送到同一网络上的客户端。
这是我的代码:
from socket import *
serverPort = 8000
serverSocket = socket(AF_INET,SOCK_STREAM)
# Prepare a sever socket
serverSocket.bind(('',serverPort)) # binds socket to port 8000
serverSocket.listen(1) # waiting for client to initiate connection
while True:
# Establish the connection
print('Ready to serve...')
connectionSocket,addr = serverSocket.accept()
try:
message = connectionSocket.recv(1024)
filename = message.split()[1]
f = open(filename[1:].decode())
outputdata = f.read()
# Send one HTTP header line into socket
http_response = 'HTTP/1.1 200 OK\n'
connectionSocket.send(http_response.encode())
# Send the content of the requested file to the client
for i in range(0,len(outputdata)):
connectionSocket.send(outputdata[i].encode())
connectionSocket.send("\r\n".encode())
connectionSocket.close()
except IOError:
connectionSocket.send("\r\n".encode())
# DO LATER
serverSocket.close()
sys.exit()
这是我简单的html页面:
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>You have successfully accessed the Web Server</p>
</body>
</html>
到目前为止,每当我运行服务器并将其浏览器定向到该服务器时,我只会得到以下服务:
<p>You have successfully accessed the Web Server</p>
此后还有body和html标签。检查页面源没有标题。
我在尝试访问服务器时运行了Wireshark,实际上好像只是通过“您已经成功访问了Web服务器”进行发送。尽管事实上打印功能显示我肯定是通过TCP连接发送文件中的所有数据。
有人知道这个问题是什么吗?
解决方法
发送协议答案和标头后,实际响应将在两个\r\n
序列之后。
使用此固定代码:
from socket import *
serverPort = 8000
serverSocket = socket(AF_INET,SOCK_STREAM)
# Prepare a sever socket
serverSocket.bind(('',serverPort)) # binds socket to port 8000
serverSocket.listen(1) # waiting for client to initiate connection
while True:
# Establish the connection
print('Ready to serve...')
connectionSocket,addr = serverSocket.accept()
try:
message = connectionSocket.recv(1024)
filename = message.split()[1]
f = open(filename[1:].decode())
outputdata = f.read()
# Send one HTTP header line into socket
http_response = 'HTTP/1.1 200 OK\n'
connectionSocket.send(http_response.encode())
connectionSocket.send("\r\n".encode())
connectionSocket.send("\r\n".encode())
# Send the content of the requested file to the client
for i in range(0,len(outputdata)):
connectionSocket.send(outputdata[i].encode())
connectionSocket.close()
except IOError:
# DO LATER
serverSocket.close()
sys.exit()
,
我会使用matrixfunc(props)
库
http.server
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。