我正在编写第一个Python套接字编程代码,但无法弄清楚出了什么问题。我输入正在运行该程序的服务器的IP地址以及端口号和我要接收的文件。我应该在浏览器中收到文件,并且套接字应该关闭。相反,服务器将打印行“准备服务...”打印三遍,在浏览器中显示“404 Not Found”,并且从不关闭套接字。有人有什么想法吗?

#import socket module
from socket import *
serverSocket = socket(AF_INET, SOCK_STREAM)
#Prepare a sever socket
serverSocket.bind(('', 12006))
serverSocket.listen(1)
while True:
    print 'Ready to serve...'
    #Establish the connection
    connectionSocket, addr = serverSocket.accept()
    try:
        message = connectionSocket.recv(1024)
        filename = message.split()[1]
        f = open(filename[1:])
        outputdata = f.read()
        f.close()
        #Send one HTTP header line into socket
        connectionSocket.send('HTTP/1.0 200 OK\r\n\r\n')
        #Send the content of the requested file to the client
        for i in range(0, len(outputdata)):
            connectionSocket.send(outputdata[i])
        connectionSocket.close()
    except IOError:
        #Send response message for file not found
        connectionSocket.send('404 Not Found')
        #Close client socket
        connectionSocket.close()
serverSocket.close()

最佳答案

谢谢大家的帮助。我弄清楚出了什么问题。我已将HTML重命名为“HelloWorld.html”,然后Windows自动将.html添加到文件末尾。因此,为了访问该文件,我需要输入HelloWorld.html.html。我更改了文件名,然后此代码运行完美。

09-17 11:46