Python 实现一个简单的http服务器

来源:互联网 发布:ubuntu gtx1080 驱动 编辑:程序博客网 时间:2024/04/30 09:59

背景

原文链接:http://blog.csdn.net/ordeder/article/details/22490373

写一个python脚本,实现简单的http服务器功能:

1.浏览器中输入网站地址:172.20.52.163:20014

2.server接到浏览器的请求后,读取本地的index.html文件的内容,回发给浏览器 

代码实现

server.py

[python] view plaincopy在CODE上查看代码片派生到我的代码片
  1. #!/usr/bin/python  
  2. import socket  
  3. import signal  
  4. import errno  
  5. from time import sleep   
  6.   
  7.   
  8. def HttpResponse(header,whtml):  
  9.     f = file(whtml)  
  10.     contxtlist = f.readlines()  
  11.     context = ''.join(contxtlist)  
  12.     response = "%s %d\n\n%s\n\n" % (header,len(context),context)  
  13.     return response  
  14.   
  15. def sigIntHander(signo,frame):  
  16.     print 'get signo# ',signo  
  17.     global runflag  
  18.     runflag = False  
  19.     global lisfd  
  20.     lisfd.shutdown(socket.SHUT_RD)  
  21.   
  22. strHost = "172.20.52.163"  
  23. HOST = strHost #socket.inet_pton(socket.AF_INET,strHost)  
  24. PORT = 20014  
  25.   
  26. httpheader = '''''\ 
  27. HTTP/1.1 200 OK 
  28. Context-Type: text/html 
  29. Server: Python-slp version 1.0 
  30. Context-Length: '''  
  31.   
  32. lisfd = socket.socket(socket.AF_INET,socket.SOCK_STREAM)  
  33. lisfd.bind((HOST, PORT))  
  34. lisfd.listen(2)  
  35.   
  36. signal.signal(signal.SIGINT,sigIntHander)  
  37.   
  38. runflag = True  
  39. while runflag:  
  40.     try:  
  41.         confd,addr = lisfd.accept()  
  42.     except socket.error as e:  
  43.         if e.errno == errno.EINTR:  
  44.             print 'get a except EINTR'  
  45.         else:  
  46.             raise  
  47.         continue  
  48.   
  49.     if runflag == False:  
  50.         break;  
  51.   
  52.     print "connect by ",addr  
  53.     data = confd.recv(1024)  
  54.     if not data:  
  55.         break  
  56.     print data  
  57.     confd.send(HttpResponse(httpheader,'index.html'))  
  58.     confd.close()  
  59. else:  
  60.     print 'runflag#',runflag  
  61.   
  62. print 'Done'  

index.html

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. <html>  
  2.  <head>  
  3.      <title>Python Server</title>  
  4.  </head>  
  5.  <body>  
  6.     <h1>Hello python</h1>  
  7.     <p>Welcom to the python world</br>  
  8.  </body>  
  9. </html>  

测试

测试结果:

root@cloud2:~/slp/pythonLearning/socket# ./server_v1.py 
connect by  ('172.20.52.110', 6096)
GET / HTTP/1.1
Host: 172.20.52.163:20014
Connection: keep-alive
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
User-Agent: Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36
Accept-Encoding: gzip,deflate,sdch
Accept-Language: zh-CN,zh;q=0.8,en;q=0.6

浏览器

0 0
原创粉丝点击