-
Notifications
You must be signed in to change notification settings - Fork 0
/
HTTPServer_with_threading( full implementation).py
72 lines (61 loc) · 2.32 KB
/
HTTPServer_with_threading( full implementation).py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer # to convert the response to bits
from os import curdir, sep # to search in the server folder
from SocketServer import ThreadingMixIn
import threading
PORT = 8888
HOST = "" #local host
#This class will handles any incoming request from the browser
class myHandler(BaseHTTPRequestHandler):
#Handler for the GET requests from browser
def do_GET(self):
#Contains the request path.
if self.path=="/":
self.path="/home.html"
try:
#Check the file extension required and set the right mime type
sendReply = False
if self.path.endswith(".html"):
mimetype='text/html'
sendReply = True
if self.path.endswith(".jpg"):
mimetype='image/jpg'
sendReply = True
if self.path.endswith(".gif"):
mimetype='image/gif'
sendReply = True
if self.path.endswith(".png"):
mimetype='image/png'
sendReply = True
if self.path.endswith(".js"):
mimetype='application/javascript'
sendReply = True
if self.path.endswith(".css"):
mimetype='text/css'
sendReply = True
if sendReply == True:
#Open the static file requested and send it
thread= threading.currentThread().getName()
f = open(curdir + sep + self.path) #open teh current directory and choose the speciefic file
self.send_response(200)
self.send_header('Content-type',mimetype)
self.end_headers()
# wfile Contains the output stream for writing a response back to the client.
#self.wfile.write(thread)
#self.wfile.write("\n")
self.wfile.write(f.read())
f.close()
return
except IOError:
self.send_error(404,'File Not Found: %s' % self.path)
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
"""Handle requests in a separate thread."""
try:
#Create a web server and define the handler to manage the
#incoming request
server = ThreadedHTTPServer((HOST, PORT), myHandler)
print 'Started httpserver on port ' , PORT
#Wait forever for incoming htto requests
server.serve_forever()
except KeyboardInterrupt:
print '^C received, shutting down the web server'
server.socket.close()