next up previous contents index
Next: C. Fundamental Modeling Concepts Up: B. Sources Previous: B. Sources   Contents   Index


B.1 Simple HTTP Server


   1 #!/usr/bin/env python
   2 
   3 # simple HTTP Server in Python 2
   4 
   5 import socket, string, os
   6 from stat import *
   7 
   8 # Please change setting to your needs
   9 PORT          = 8081 # Arbitrary non-privileged server
  10 DOCUMENT_ROOT = "Test-HTML/"
  11 
  12 # procedure process_request
  13 def process_request( clientsocket, address ):
  14 
  15 # read HTTP request
  16     # Define Response Headers
  17     responsePrefix = "HTTP/1.0 200 OK\nServer:HPIserver/1.0\n"
  18     response_NotSupported = """HTTP/1.0 400 Bad Request
  19 Server: HPIserver/1.0\nConnection: close
  20 Content-Type: text/html; charset=iso-8859-1\n
  21 <HTML><HEAD><TITLE>400 Bad Request</TITLE></HEAD>\n"""
  22     response_FileNotFound = """HTTP/1.0 404 Not Found\nServer: HPIserver/1.0
  23 Connection: close\nContent-Type: text/html; charset=iso-8859-1\n
  24 <html><head><title>File not found</title></head>\n"""
  25 
  26     # Create File descriptor for request to read the first line of the request
  27     clientsockfile = clientsocket.makefile('rw')
  28     requestline = clientsockfile.readline();
  29 
  30 # process GET method only
  31     requestwords = string.split( requestline )
  32     if requestwords[0]  == 'GET':
  33 
  34 # search file
  35 	try:
  36 	    if requestwords[1] == '/':
  37 	        # assume index.html was requested (no directory view)
  38 	        requestwords[1] = '/index.html'
  39 	    filestatus = os.stat( DOCUMENT_ROOT + requestwords[1] )
  40 	    if S_ISREG(filestatus[ST_MODE]): # Regular file ?
  41 	        # detect file size using stat()
  42 	        filesize = filestatus[ST_SIZE]
  43 		# open file in binary mode
  44 	        file = open(DOCUMENT_ROOT + requestwords[1], 'rb')
  45 	    else:
  46 	        raise OSError
  47 	except OSError:
  48             clientsocket.send( response_FileNotFound )
  49             clientsocket.send( "<body> File: " + requestwords[1] +
  50 	                       " not found</body>\n</html>\n" )
  51 	else:
  52 
  53 # Detect file's MIME type by suffix.
  54 	    suffix = string.split( requestwords[1], '.' )[-1]
  55 	    # text/html image/gif image/jpeg audio/midi application/java
  56 	    if   suffix == 'html': filetype = 'text/html'
  57 	    elif suffix == 'gif' : filetype = 'image/gif'
  58 	    elif suffix == 'jpg' : filetype = 'image/jpeg'
  59 	    elif suffix == 'mid' : filetype = 'audio/midi'
  60 	    elif suffix == 'class' : filetype = 'application/java'
  61 	    else: filetype = "unknown"
  62 
  63 # send response
  64 	    # Send response header
  65             clientsocket.send( responsePrefix )
  66 	    clientsocket.send( "content-type: "+ filetype + "\n" )
  67 	    clientsocket.send( "content-length: "+ repr(filesize) + "\n" )
  68             clientsocket.send( "\n" )
  69 
  70 	    # send file in 1024 byte chunks
  71             while 1:
  72                data = file.read(1024)
  73 	       if not data:
  74                    break
  75                clientsocket.send( data )
  76     else:
  77         clientsocket.send( response_NotSupported )
  78 	clientsocket.send( "<body> request: " + requestline +
  79 	                   "</body>\n</html>\n" )
  80 
  81     # close Filedescriptor for request
  82     clientsockfile.close()
  83 
  84 
  85 #-----------------------------------------
  86 # Server main
  87 
  88 
  89 # Initialization
  90 
  91 # Open server socket
  92 
  93   # inet Socket (not UNIX), Type Stream (not datagram)
  94 serversocket = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
  95 serversocket.bind((socket.gethostname(), PORT)) # bind to Port PORT
  96   # tell OS to activate port for a maximum
  97   # of 1 connection simultanouslyserversocket.listen(1)
  98 
  99 # request-response loop
 100 try:
 101     while 1:
 102         # wait for request and establish connection
 103         ( clientsocket, address ) = serversocket.accept()
 104         process_request( clientsocket, address )
 105         # Close connection
 106         clientsocket.close()
 107 finally:
 108 # Deactivation
 109     serversocket.close()



Apache Modeling Portal Home Apache Modeling Portal
2004-10-29