Simple HttpServer in Twisted Python

May 27, 2008 at 8:25 am (Programming, Uncategorized)

this is a sample code of http server programmed in twisted python
#httpserver.py
#!/usr/bin/python
import sys
from twisted.protocols import basic
from twisted.web import server,resource,http
from twisted.internet.protocol import Protocol

class HttpProtocol(basic.LineReceiver,Protocol):

def __init__(self):
self.lines = []

def connectionMade(self):
self.sendLine(“HTTP/1.0 200 OK”)
self.sendLine(“Content-Type:text/plain”)
self.sendLine(“”)

def lineReceive(self,line):
# your code goes here: process the line you receive
print line

class HttpFactory(http.HTTPFactory):

def __init__(self):
self.protocol = HttpProtocol

def onClientConnected(self):
print “Connected”

reactor.listenTCP(8080,HttpFactory())
reactor.run()

running on the terminal
$ python httpserver.py
as the reactor.run called, your http server is now listening on port 8080

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: