GMgKe586q6suSQnyqZLlGCooeWM

Pages

Search

Monday, May 2, 2011

Python - Bulding Web Server

Here's a short code on how to build workable web server:

name: server.py
import socket

HOST = ''
PORT = 6003

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))
server.listen(2)
conn, addr = server.accept()

print 'Connected by', addr

# initial lines
data = 'HTTP/1.0 404 Not Found\n'

# header lines - all are optional
data = data + 'Date: Fri, 31 Dec 2011 10:12:13 GMT\n'
data = data + 'Content-Type: text/html\n'
data = data + 'Content-Length: 22\n'
data = data + 'Server: Lucia Web Server\n'

# separating lines. needed
data = data + '\n'

# body
data = data + '<html><head><title>Hello World</title></head><body>'
data = data + '<h1>hello World</h1></body></html>'

# receiving the request headers from browser
datas = conn.recv(1024)
print datas


# send the response header plus the body
conn.send(data)
conn.close()



These the request header of the browser:

GET /index.html HTTP/1.1
Host: localhost:6003
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.17) Gecko/2
0110420 SVD Firefox/3.6.17
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive


Accessed from telnet
>>telnet
telnet>> open localhost 6003 HTTP/1.0 /index.hmtl

Share/Bookmark

No comments:

Post a Comment