如何解决为什么 chrome 无法从我的幼稚服务器接收文件?
我想检查一下我对 HTTP 的理解,写了一个非常简单的服务器来监听 localhost:4567,如果有人向这个地址发送 HTTP 请求,它会将 index.html 发送回客户端。
>#import socket module
from socket import *
import sys # In order to terminate the program
serverSocket = socket(AF_INET,SOCK_STREAM) #Prepare a sever socket
host = "localhost"
port = 4567
serverSocket.bind((host,port))
serverSocket.listen(5)
#Establish the connection
print('Ready to serve...')
connectionSocket,addr = serverSocket.accept()
print("accept from ",addr)
try:
message = connectionSocket.recv(1024).decode()
print(message)
filename = message.split()[1][1:] # a dirty way to get index.html from "GET /index.html HTTP/1.1"
with open(filename) as f:
outputdata = f.read()
#Send one HTTP header line into socket
connectionSocket.sendall("HTTP/1.1 200 ok\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.send("\r\n".encode())
except IOError:
#Send response message for file not found
print("file not find")
connectionSocket.sendall("HTTP/1.1 404 not found\r\n".encode())
connectionSocket.send("\r\n".encode())
connectionSocket.close()
serverSocket.close()
sys.exit()#Terminate the program after sending the corresponding data
但是当我认为一切正常并在 chrome 中输入 http://localhost:4567/index.html 时,chrome 大喊它无法访问该网站并且 localhost 拒绝了请求。但是当我尝试打印一些日志时,我发现我的简单服务器实际上接受了来自 chrome 的请求并将消息发送回 chrome。我的实现有什么问题?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。