python - 简单的python Webserver socket编程
问题描述
我无法让我的网络服务器连接到我的 python,如果我这样做了,它会直接进入 IOError 并打印出 404 Not Found 而不是打印我拥有的 html 文件。
我已经尝试运行此代码并修复它很多天了,但我就是无法找出问题所在。我在不同的计算机上尝试过,然后只有一台计算机,我得到的只是它会跳到 404 Not found。
我使用 127.0.0.1:6789/helloworld.html 连接它。
import sys
serverPort = 6789
serverSocket = socket(AF_INET, SOCK_STREAM)
#serverName = ''
serverSocket.bind(("",serverPort))
serverSocket.listen(1)
print ('the web server is up on port: ', serverPort)
while True:
#Establish the connection
print('Ready to serve...')
(connectionSocket, addr) = serverSocket.accept()
print("connection is from: " + str (addr))
try:
message = connectionSocket.recv(1024).decode()
filename = message.split()[1]
f = open(filename[1:])
outputdata = f.read()
print ("output data is: ",outputdata)
connectionSocket.send(('HTTP/1.1 200 OK\r\n').encode())
connectionSocket.send(message.encode())
outputdata = f.read()
for i in range(0, len(outputdata)):
connectionSocket.send(outputdata[i].encode())
connectionSocket.send(("\r\n").encode())
connectionSocket.close()
except IOError:
connectionSocket.send(('HTTP/1.1 404 Not Found\r\n\r\n').encode())
connectionSocket.send(("<html><body><h1> 404 Not Found </h1></body></html>\r\n\r\n").encode())
connectionSocket.close()
serverSocket.close()
sys.exit()
然后我拥有的 html 文件与 helloworld.html 保存在与此 webserver.py 相同的文件夹中
<!DOCTYPE html>
<html>
<body>
<h1> Hello World </h1>
<h2> How are you? </h2>
</body>
</html>
我希望它以 Hello World How are you 的形式在浏览器中运行,但实际输入被跳过到 404 Not Found。
解决方案
推荐阅读
- python - Can't install gcloud on Amazon Linux : invalid syntax
- swift - 如何替换字符串中出现的有限次数
- sql - 对 ODBC 表使用多个左连接的查询失败
- python - Pyspark 用 NULL 替换 NaN
- android - Java 8 和安卓
- android - 具有不同 ListView 数据的相同小部件
- php - 将任意变量括在单引号中会阻止 eval() 执行代码吗?
- c - 了解 C 中的 unsigned char 左旋转
- r - roxygen 如何在函数参数中处理 ...
- reactjs - AppBar Material UI 问题