Search code examples
pythonwebserver

Very basic Python web server - strange issue


I'm just starting out with Python and I'm trying to code a simple web server. Everything seems to be work except I'm having one small problem. When I request a specific file like Test.html from my web server, the data in the HTML file is repeated over and over in my client like its stuck in a loop. So instead of seeing just "Test" displayed in the web client once, I see "Test Test Test Test Test Test...many times over". This is probably a simple error but I was hoping someone could point me in the right direction.

Thanks for you help!

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

Solution

  • You are stuck in a loop :)

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

    You're sending the contents of outputdata the number of times however long the length of the file is.

    You only need connectionSocket.send(outputdata) without the for..loop to send it once.

    Also, make sure you close the file you read the contents from. (f.close())