python3實現的多執行緒httpserver
阿新 • • 發佈:2019-01-24
我們主要使用python3提供的http模組來實現一個python的http伺服器。在瀏覽器的位址列裡面輸入http://127.0.0.1:8080就可以檢視這個程式的執行結果了。
另外在這個程式裡,我們為了提供效能,使用了多執行緒的技術。主要是使用socketserver提供的ThreadingMixIn模組來實現的,具體如下下面的程式碼所示:
- from http.server import BaseHTTPRequestHandler
- from http.server import HTTPServer
- from socketserver import ThreadingMixIn
-
hostIP = ''
- portNum = 8080
- class mySoapServer( BaseHTTPRequestHandler ):
- def do_head( self ):
- pass
- def do_GET( self ):
- try:
- self.send_response( 200, message = None )
- self.send_header( 'Content-type', 'text/html' )
- self.end_headers()
-
res = ''
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
- <HTML>
- <HEAD><META content="IE=5.0000" http-equiv="X-UA-Compatible">
- <META content="text/html; charset=gb2312" http-equiv=Content-Type>
- </HEAD>
-
<BODY>
- Hi, www.perlcn.com is a good site to learn python!
- </BODY>
- </HTML>
- '''
- self.wfile.write( res.encode( encoding = 'utf_8', errors = 'strict' ) )
- except IOError:
- self.send_error( 404, message = None )
- def do_POST( self ):
- try:
- self.send_response( 200, message = None )
- self.send_header( 'Content-type', 'text/html' )
- self.end_headers()
- res = '''
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
- <HTML>
- <HEAD><META content="IE=5.0000" http-equiv="X-UA-Compatible">
- <META content="text/html; charset=gb2312" http-equiv=Content-Type>
- </HEAD>
- <BODY>
- Hi, www.perlcn.com is a good site to learn python!
- </BODY>
- </HTML>
- '''
- self.wfile.write( res.encode( encoding = 'utf_8', errors = 'strict' ) )
- except IOError:
- self.send_error( 404, message = None )
- class ThreadingHttpServer( ThreadingMixIn, HTTPServer ):
- pass
- myServer = ThreadingHttpServer( ( hostIP, portNum ), mySoapServer )
- myServer.serve_forever()
- myServer.server_close()
在瀏覽器的位址列裡面輸入http://127.0.0.1:8080,測試結果如下:
127.0.0.1 - - [13/Jul/2013 15:22:38] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [13/Jul/2013 15:22:38] "GET /favicon.ico HTTP/1.1" 200 -