|
|
|
Introduction to Python
(by Ilan Schnell)
|
from SocketServer import BaseRequestHandler, TCPServer
import sys
if len(sys.argv) != 2:
print 'USAGE: %s <port>' % sys.argv[0]
sys.exit(2)
def htmlSave(s):
htmlentList = [ ('&','&'), ('<','<'), ('>','>') ]
return reduce( lambda c, (a,b): c.replace(a,b), htmlentList, s )
class RequestHandler(BaseRequestHandler):
def handle(self):
print "Client connected:", self.client_address
content="""<html><head><title>HTTP Server</title></head><body>
<h2>Information about this HTTP/TCP request:</h2>
<p>IP: <b>%s</b><br />
Port: <b>%s</b></p>
<h4>Message:</h4>
<pre style='border: solid 1px #bdf; background-color: #def;'>%s</pre>
</body></html>
""" % ( self.client_address[0],
self.client_address[1],
htmlSave(self.request.recv(2**16).replace('\r','<CR>')) )
self.request.sendall( """HTTP/1.0 200 OK\r
Content-Type: text/html; charset=utf-8\r
Content-Length: %s\r
\r\n%s""" % ( len(content), content ))
self.request.close()
TCPServer(('',int(sys.argv[1])), RequestHandler).serve_forever()