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()
你爲什麼要這樣做?只是'進口燒瓶' –