【问题标题】:My HTTP response from custom web server doesn't get recognized as a HTTP message我来自自定义 Web 服务器的 HTTP 响应没有被识别为 HTTP 消息
【发布时间】:2020-03-01 05:24:53
【问题描述】:

我正在从一本书中学习套接字和套接字编程,我想通过创建一个简单的 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 响应消息。

【问题讨论】:

  • “顺便说一句。我从网页复制了这个 HTTP 响应消息。” - 无论来源是什么,除了内容之外,它都是错误的(或者你复制的错误) - 答案中提到的长度。没有Connection: Closed,只有Connection: close(即关闭未关闭)。

标签: python-3.x sockets http tcp


【解决方案1】:

我可以让它与它一起工作(端口已更改,以便它在 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 :)

【讨论】:

    猜你喜欢
    • 2021-01-09
    • 1970-01-01
    • 2016-02-05
    • 1970-01-01
    • 2018-02-18
    • 1970-01-01
    • 2016-09-01
    • 1970-01-01
    • 2011-02-12
    相关资源
    最近更新 更多