python 用socket写一个简单的http server

 1 import socket
 2 
 3 host = ''
 4 port = 8000
 5 
 6 text_content = b'''HTTP/1.x 200 OK
 7 Content-Type: text/html
 8 
 9 <head>   #上面的空行千万不要省略
10 <title>WOW</title>
11 </head>
12 <html>
13 <P>Wow, Python Server</P>
14 <IMG src='test.jpg'/>
15 </html>
16 '''
17 
18 f = open('test.jpg','rb')
19 pic_content = b'''
20 HTTP/1.x 200 OK
21 Content-Type: image/jpg
22 
23 '''    # 上面的空行千万不要省略
24 
25 pic_content = pic_content + f.read()
26 f.close()
27 
28 s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
29 s.bind((host,port))
30 
31 while True:
32     s.listen(10)
33     conn,addr = s.accept()
34     request = bytes.decode(conn.recv(1024))
35     # print(request,type(request))
36     method = request.split(' ')[0]
37     src = request.split(' ')[1]
38     if method == 'GET':
39         if src == '/test.jpg':
40             content = pic_content
41         else:
42             content = text_content
43         print('Connect by',addr)
44         print('Requst is:',request)                    
45         print('content:-------------------------',content)  #调试代码
46         conn.sendall(content)
47     conn.close()
48 s.close()

 

实现效果:

 

posted @ 2016-12-18 21:22  Vincen_shen  阅读(563)  评论(0)    收藏  举报