同时处理多个客户端请求,并且为不同的CLIENT开不同的线程处理。
这个东东,就显然实用性稍强了一些。(FORK和THREAD方式均可,但各有应用)
#!/usr/bin/env python from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler from SocketServer import ThreadingMixIn import time,threading starttime = time.time() class RequestHandler(BaseHTTPRequestHandler): """Definintion of the request hadnler.""" def _writeheaders(self, doc): """Write the HTTP headers for the document. If there is no documnet, send a 404 error code;""" if doc is None: self.send_response(404) else: self.send_response(200) #Always server up HTML for now. self.send_header('Content-type', 'text/html') self.end_headers() def _getdoc(self, filename): """Handle a request for a document """ global starttime if filename == '/': return """ <HTML><HEAD><TITLE>sample python page</TITLE></HEAD> <BODY> THIS IS A SAMPLE PAGE. </BODY></HTML> """ elif filename == '/stats.html': return """ <HTML><HEAD><TITLE>Status</TITLE></HEAD> <BODY> This server has veen running for %d seconds. </BODY></HTML> """ % int(time.time() - starttime) else: return None def do_HEAD(self): """Handle a request for headers only""" doc = self._getdoc(self.path) self._writeheaders(doc) def do_GET(self): """Handle a request for headers and body""" print "Handling with thread", threading.currentThread().getName() doc = self._getdoc(self.path) self._writeheaders(doc) if doc is None: self.wfile.write(""" <HTML><HEAD><TITLE>Not found</TITLE></HEAD> <BODY> The requested document '%s' was not found. </BODY></HTML>""" % self.path) else: self.wfile.write(doc) class ThreadingHTTPServer(ThreadingMixIn, HTTPServer): pass serveraddr = ('',8765) srvr = ThreadingHTTPServer(serveraddr, RequestHandler) srvr.serve_forever()
时间: 2024-09-20 17:17:20