Ich beginne gerade mit Python und versuche, einen einfachen Webserver zu programmieren. Alles scheint Arbeit zu sein, außer dass ich ein kleines Problem habe. Wenn ich eine bestimmte Datei wie Test.html von meinem Webserver anfordere, werden die Daten in der HTML-Datei in meinem Client immer wieder wiederholt, wie es in einer Schleife steckt. Anstatt nur einmal "Test" im Web Client zu sehen, sehe ich "Test Test Test Test Test Test ... viele Male". Dies ist wahrscheinlich ein einfacher Fehler, aber ich hatte gehofft, dass jemand mich in die richtige Richtung zeigen könnte.Sehr einfacher Python-Webserver - seltsames Problem
Danke für Ihre Hilfe!
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()
warum würden Sie das tun? nur 'Importflasche' –