非常基本的Python Web服务器 - 奇怪的问题

时间:2017-10-09 17:36:30

标签: python webserver

我刚刚开始使用Python,我正在尝试编写一个简单的Web服务器。除了我遇到一个小问题外,一切似乎都有效。当我从我的Web服务器请求像Test.html这样的特定文件时,HTML文件中的数据会在我的客户端中反复重复,就像它停留在循环中一样。因此,我没有看到网络客户端中只显示“测试”,而是看到“测试测试测试测试测试...多次”。这可能是一个简单的错误,但我希望有人能指出我正确的方向。

谢谢你的帮助!

import socket
import sys

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Socket Created!!")

try:
#bind the socket
    #fill in start
        server_address = ('localhost', 6789)
        serversocket.bind(server_address)
    #fill in end
except socket.error as msg:
    print("Bind failed. Error Code: " + str(msg[0]) + "Message: " + 
msg[1])
    sys.exit()  
print("Socket bind complete")

#start listening on the socket
#fill in start
serversocket.listen(1)
#fill in end
print('Socket now listening')

while True: 
#Establish the connection 
    connectionSocket, addr = serversocket.accept()
    print('source address:' + str(addr))
    try:
    #Receive message from the socket
        message = connectionSocket.recv(1024)  
        print('message = ' + str(message))
        #obtian the file name carried by the HTTP request message
        filename = message.split()[1] 
        print('filename = ' + str(filename))
        f = open(filename[1:], 'rb') 
        outputdata = f.read()
        #Send the HTTP response header line to the socket
        #fill in start
        connectionSocket.send(bytes('HTTP/1.1 200 OK\r\n\r\n','UTF-
8'))
        #fill in end
        #Send the content of the requested file to the client
        for i in range(0, len(outputdata)):  
            connectionSocket.send(outputdata)

        #close the connectionSocket
        #fill in start
        connectionSocket.close()
        #fill in end

        print("Connection closed!")
    except IOError: 
        #Send response message for file not found 
        connectionSocket.send(bytes("HTTP/1.1 404 Not 
Found\r\n\r\n","UTF-8"))
        connectionSocket.send(bytes("<html><head></head><body><h1>404 
Not Found</h1></body></html>\r\n","UTF-8"))

#Close the client socket 
        #fill in start
        connectionSocket.close()
serverSocket.close()

1 个答案:

答案 0 :(得分:3)

你被困在一个循环中:)

    #fill in end
    #Send the content of the requested file to the client
    for i in range(0, len(outputdata)):  
        connectionSocket.send(outputdata)

您发送的内容为outputdata,但文件的长度是多长。

您只需要connectionSocket.send(outputdata)而不需要for..loop发送一次。

此外,请确保关闭从中读取内容的文件。 (f.close()