我来自自定义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响应消息。

xiaojiissb 回答:我来自自定义Web服务器的HTTP响应未识别为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:)

本文链接:https://www.f2er.com/3163691.html

大家都在问