File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1- # TODO
1+ try :
2+ import usocket as socket
3+ except :
4+ import socket
5+
6+ okResponse = b"""\
7+ HTTP/1.1 200 OK
8+
9+ %s
10+ """
11+
12+ badResponse = b"""\
13+ HTTP/1.1 400 Bad Request
14+ Content-Type: text/html; charset=utf-8
15+
16+ <h1>400 Bad Request</h1>
17+ """
18+
19+ def main ():
20+ headers = b"""\
21+ HTTP/1.1 200 OK
22+ Content-Type: text/html; charset=utf-8
23+ Content-Encoding: gzip
24+ Content-Length: %d
25+
26+ """
27+
28+ # read the gzipped html
29+ f = open ('hello_world.min.html.gz' ,'rb' )
30+ html = f .read ()
31+ f .close ()
32+
33+ # set the content length
34+ headers = headers % len (html )
35+
36+ # create server
37+ s = socket .socket ()
38+ s .setsockopt (socket .SOL_SOCKET , socket .SO_REUSEADDR , 1 )
39+ s .bind (('0.0.0.0' , 80 ))
40+ s .listen (5 )
41+ print ("Listening for http requests on port 80" )
42+
43+ # process requests
44+ while True :
45+ client_s , client_addr = s .accept ()
46+
47+ req = client_s .recv (4096 )
48+
49+ print ("Request:\n %s\n " % req )
50+
51+ # grab some variables from request header
52+ # eg. GET /on HTTP/1.1
53+ method , path , protocol = req .split (b'\r \n ' ,1 )[0 ].split ()
54+
55+ if path == b'/' :
56+ client_s .send (headers )
57+ client_s .sendall (html )
58+ else :
59+ client_s .send (badResponse )
60+ client_s .close ()
61+
62+ main ()
You can’t perform that action at this time.
0 commit comments