python-3.x - 我来自自定义 Web 服务器的 HTTP 响应没有被识别为 HTTP 消息
问题描述
我正在从一本书中学习套接字和套接字编程,我想通过创建一个简单的 Web 服务器来进行实验。这是代码:
import socket
welcomingSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
welcomingSocket.bind(('', 80))
welcomingSocket.listen(1)
while True:
connectionSocket, addr = welcomingSocket.accept()
request = connectionSocket.recv(1024)
#Doesn't get recognised as an http message by wireshark
response = "HTTP/1.1 200 OK\r\n\
Date: Mon, 27 Jul 2009 12:28:53 GMT\r\n\
Server: Apache/2.2.14 (Win32)\r\n\
Last-Modified: Wed, 22 Jul 2009 19:15:56 GMT\r\n\
Content-Length: 88\r\n\
Content-Type: text/html\r\n\
Connection: Closed\r\n\
\r\n\
<html>\r\n\
<body>\r\n\
<h1>Hello, World!</h1>\r\n\
</body>\r\n\
</html>\r\n\
\r\n"
connectionSocket.send(response.encode())
connectionSocket.close()
一切正常,除了当我通过浏览器访问我的 IP 时,我看不到该网站。此外,我使用 Wireshark 查看发生了什么,发现我的响应没有被 Wireshark 识别为 HTTP 消息,仅作为 TCP 段。
我真的很想知道为什么它不起作用。是因为我发送的日期不正确还是消息的格式不正确?
顺便提一句。我从网页复制了这个 HTTP 响应消息。
解决方案
我可以让它与它一起工作(端口已更改,使其在 Linux 下作为普通用户运行:))
import socket
welcomingSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
welcomingSocket.bind(('127.0.0.1', 8196))
welcomingSocket.listen(1)
while True:
connectionSocket, addr = welcomingSocket.accept()
request = connectionSocket.recv(1024)
response = "HTTP/1.1 200 OK\r\n\
Date: Mon, 27 Jul 2009 12:28:53 GMT\r\n\
Server: Apache/2.2.14 (Win32)\r\n\
Last-Modified: Wed, 22 Jul 2009 19:15:56 GMT\r\n\
Content-Length: 60\r\n\
Content-Type: text/html\r\n\
Connection: Closed\r\n\
\r\n\
<html>\r\n\
<body>\r\n\
<h1>Hello, World!</h1>\r\n\
</body>\r\n\
</html>\r\n\
\r\n"
connectionSocket.send(response.encode())
connectionSocket.close()
基本上,错误就在这条线上
Content-Length: 88
那必须是60。
这是错误的长度导致 Chromium 拒绝该页面(它会在其 Web 开发人员工具中告诉您有关它的信息,包括特定且有用的错误消息)。有趣的是,Firefox 在这里显示原始变体(内容长度错误)没有问题。
更改了内容长度后,Wireshark 也接受它作为 HTTP :)
推荐阅读
- excel - 使用密码保护已关闭的工作簿
- python - 如何用“PROJ_LIB”解决这个问题?
- eclipse - libopencv_highgui.so.3.4:无法打开共享对象文件:eclipse ide中没有这样的文件或目录用于交叉编译
- javascript - 仅当输入有效时才显示按钮
- java - Java中的重叠对象
- c# - 使用单独的域和持久层处理聚合内部的更改
- scripting - Indesign脚本按顺序获取页面的所有文本框
- python - 在python中打印某个单词后如何使文本出现
- python-3.x - FitEllipse opencv-python > 4
- iteration - 如何使用 Racket 将递归过程(重复 fn)重写为迭代过程?