微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么 chrome 无法从我的幼稚服务器接收文件?

如何解决为什么 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 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?