tags:

views:

85

answers:

1

This is a simple server. When you open the browser type into the address of the server, and it will response a status code and the content of the requested html. But when I add this sentence "connectionSocket.send('HTTP/1.1 200 OK')", nothing returned. When I removed it, the html returned. And another problem is when I send the request by web browser, there are two connect sent to the server, and one displays it wanna find a file named favicon.ico, but of course it is a IOError because there is not such a file on my server's root directory. Code is attached and thanks for help.


#import socket module

from socket import *
serverSocket = socket(AF_INET,SOCK_STREAM)
#prepare a server socket

serverSocket.bind(('192.168.0.101', 8765))
serverSocket.listen(1)

while True:

    #Establish the connection

    print 'Ready to serve...'
    connectionSocket,addr =  serverSocket.accept()
    print 'connected from',addr
    try:
        message = connectionSocket.recv(1024)
        filename = message.split()[1]
        print filename
        f = open(filename[1:])
        outputdata = f.read()

        #Send one HTTP header line into socket

        #connectionSocket.send('HTTP/1.1 200 OK')

        #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:
        print 'IOError'

        #Send response message for file not found

        connectionSocket.send('file not found')

        #Close Client socket

        connectionSocket.close()
serverSocket.close()

+2  A: 

You need to add to newlines (\r\n\r\n) to the end of the HTTP headers:

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

Also, you should probably be using a more higher level library for writing your HTTP server...

Daren Thomas
Thanks for the reply, it works. Does it mean 'HTTP/1.1 200 OK\r\n\r\n' is a formal http response header, when the browser read this line completely without even one missing letter, the browser knows this is a header?
uh, I'm not so sure. Read the HTTP specs (RFC, or just go look at Wikipedia if you don't need to know for sure). Basically, these protocols terminate header entries with newlines and separate the headers from the content with two newlines.
Daren Thomas
@user449110: Please read RFC 2616. http://www.faqs.org/rfcs/rfc2616.html. Your question is answered there. And if you're going to continue trying to write this kind of software, you **must** know the standards.
S.Lott
Here's an example webserver using higher level libs as S.Lott suggests http://fragments.turtlemeat.com/pythonwebserver.php I've based another simple application off of this code without issue.
Dana the Sane