2017-10-09 88 views
0

我剛剛開始與Python,我試圖編寫一個簡單的Web服務器。除了我有一個小問題,一切似乎都是工作。當我從我的Web服務器請求一個特定的文件(如Test.html)時,HTML文件中的數據在我的客戶端反覆重複,就像停留在循環中一樣。因此,我看到「測試測試測試測試測試...多次」,而不是隻看到Web客戶端中顯示的「測試」一次。這可能是一個簡單的錯誤,但我希望有人能指出我正確的方向。非常基本的Python網絡服務器 - 奇怪的問題

感謝您的幫助!

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() 
+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()