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