Ben Yan
Ben Yan

Reputation: 61

Simple Web Server Socket Program not working?

I'm currently doing a socket program for a simple web server that basically retrieves an HTML file from a server's file system. The server sets up perfectly and is ready to serve, however when I try to access the html file which in this case, "index.html" which is in the same directory as my WebServer.py, the browser keeps saying this page cannot be displayed. I've tried using different port numbers and different browsers to no avail.

Here is my code:

WebServer.py

from socket import *

def main():

    #Specify the port
    serverPort= 3000
    serverSocket=socket(AF_INET, SOCK_STREAM)
    serverSocket.bind(('',serverPort))
    serverSocket.listen(1) #listen for connection
    print("Web server up on port",serverPort) #print port address

    #Start thw while loop.
    while True:

        print("Ready to serve")
        connectionSocket,addr = serverSocket.accept()
        try:

            message = connectionSocket.recv(1024)
            print message,'::', message.split()[0], ':', message.split()[1]
            filename = message.split()[1]

            print(filename,'||',filename[1:])
            f = open(filename[1:])
            outputdata = f.read()
            print outputdata

            connectionSocket.send('HTTP/1.1 200 OK \r\n')
            connectionSocket.send(outputdata)
            connectionSocket.close()


        except IOError:
            pass
            #Send response message for the file not found.
            print ("404 Not Found")
            connectionSocket.send('HTTP/1.1 404 Not Found \r\n');

        #Temp break
        break
    pass
if __name__ == '__main__':
    main()

Upvotes: 1

Views: 885

Answers (1)

Steffen Ullrich
Steffen Ullrich

Reputation: 123639

    connectionSocket.send('\nHTTP/1.1 200 OK\n\n')

The leading \n at the start of the HTTP header is definitely wrong. Apart from that the line delimiter should be \r\n not \n.

    connectionSocket.send('\HTTP/1.1 404 Not Found \n\n');

This should be HTTP/1.1... and not \HTTP/1.1.... And the line delimiter is wrong too.

I have no idea where your (insufficient) understanding of HTTP comes from. But if you want to implement a server I recommend to not just have a look at a few packet captures or similar but actually study the standard which is more complex than you might imagine. That's what standards are for.

Upvotes: 1

Related Questions