The framework
import timefrom test1 import HTTPServerclass Applicatoin(object): def __init__(self,urls): self.urls = urls def __call__(self, evn, start_response): path = evn.get("PATH_INFO") print('original pathinfo %s'%path) for url,handler in self.urls: if path == url: print('----------%s--------'%path) return handler(evn,start_response) status = '404 not found' headers = [] start_response(status,headers) print('-----%s not found'%path) return '404 not found'def show_ctime(evn,start_response): status = '200 Ok' headers = [ ('Content-Type','text/plain') ] start_response(status,headers) return time.ctime()def say_hello(env,start_response): status = '200 Ok' headers = [ ('Content-Type','text/plain') ] start_response(status,headers) return 'hello'urls = [ ('/',show_ctime), ('/ctime',show_ctime), ('/sayhello',say_hello)]if __name__ == '__main__': app = Applicatoin(urls) http_server = HTTPServer(app) http_server.bind(8000) http_server.start()
The server
from socket import *import refrom multiprocessing import Processclass HTTPServer(object): def __init__(self,app): self.sSocket = socket(AF_INET,SOCK_STREAM) self.app = app self.sSocket.setsockopt(SOL_SOCKET,SO_REUSEADDR,1) def start(self): self.sSocket.listen() while True: client_socket,client_add = self.sSocket.accept() print('---%s %s---connect--'%(client_add)) handle_client_process = Process(target=self.handle_client,args=(client_socket,)) handle_client_process.start() client_socket.close() def start_response(self,status,headers): response_headers = 'HTTP/1.1 '+status+"\r\n" for header in headers: response_headers+='%s %s\r\n'%header self.response_headers = response_headers def handle_client(self,client_socket): request_data = client_socket.recv(1024) print('request data is'%request_data) requst_lines = request_data.splitlines() for line in requst_lines: print(line) requst_start_line = requst_lines[0] print('*'*10) print(requst_start_line.decode('utf-8')) file_name = re.match(r'\w+ +(/[^ ]*)',requst_start_line.decode('utf-8')).group(1) method = re.match(r'(\w)+ +/[^ ]*',requst_start_line.decode('utf-8')).group(1) print('filename = %s'%file_name) env = { 'PATH_INFO':file_name, 'METHOD':method } response_body = self.app(env,self.start_response) print('respnse body %s'%response_body) response = self.response_headers + '\r\n'+response_body print('response = %s'%response) client_socket.send(bytes(response,'utf-8')) client_socket.close() def bind(self,port): self.sSocket.bind(('',port))