首页 > 解决方案 > 简单的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。

标签: pythonsockets

解决方案


推荐阅读