Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Socket Programming Simple Web Server

I am working on my first Python socket programming code and I cannot figure out what is wrong. I type in the IP address of the server that this program is running on along with the port number and the file I am trying to receive. I should receive the file in the browser and the socket should close. Instead, the server prints out the print line 'Ready to serve...' three times, displays '404 Not Found' on the browser, and never closes the socket. Does anyone have any ideas?

#import socket module
from socket import *
serverSocket = socket(AF_INET, SOCK_STREAM)
#Prepare a sever socket
serverSocket.bind(('', 12006))
serverSocket.listen(1)
while True:
    print 'Ready to serve...'
    #Establish the connection
    connectionSocket, addr = serverSocket.accept()
    try:
        message = connectionSocket.recv(1024)
        filename = message.split()[1]
        f = open(filename[1:])
        outputdata = f.read()
        f.close()
        #Send one HTTP header line into socket
        connectionSocket.send('HTTP/1.0 200 OK\r\n\r\n')
        #Send the content of the requested file to the client
        for i in range(0, len(outputdata)):
            connectionSocket.send(outputdata[i])
        connectionSocket.close()
    except IOError:
        #Send response message for file not found
        connectionSocket.send('404 Not Found')
        #Close client socket
        connectionSocket.close()
serverSocket.close() 
like image 481
Bill Avatar asked Mar 31 '26 11:03

Bill


1 Answers

Thank you everyone for all the help. I figured out what was wrong. I had renamed my HTML to "HelloWorld.html" and then Windows automatically added .html to end of the file. So in order to have accessed the file I would of needed to type in HelloWorld.html.html. I changed the file name and then this code worked perfectly.

like image 197
Bill Avatar answered Apr 03 '26 04:04

Bill