重庆分公司,新征程启航
为企业提供网站建设、域名注册、服务器等服务
这篇文章主要介绍python如何实现简单http服务器功能,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
在桐柏等地区,都构建了全面的区域性战略布局,加强发展的系统性、市场前瞻性、产品创新能力,以专注、极致的服务理念,为客户提供网站建设、网站设计 网站设计制作按需策划,公司网站建设,企业网站建设,品牌网站制作,营销型网站,成都外贸网站建设,桐柏网站建设费用合理。背景
写一个python脚本,实现简单的http服务器功能:
1.浏览器中输入网站地址:172.20.52.163:20014
2.server接到浏览器的请求后,读取本地的index.html文件的内容,回发给浏览器
代码实现
server.py
#!/usr/bin/python import socket import signal import errno from time import sleep def HttpResponse(header,whtml): f = file(whtml) contxtlist = f.readlines() context = ''.join(contxtlist) response = "%s %d\n\n%s\n\n" % (header,len(context),context) return response def sigIntHander(signo,frame): print 'get signo# ',signo global runflag runflag = False global lisfd lisfd.shutdown(socket.SHUT_RD) strHost = "172.20.52.163" HOST = strHost #socket.inet_pton(socket.AF_INET,strHost) PORT = 20014 httpheader = '''\ HTTP/1.1 200 OK Context-Type: text/html Server: Python-slp version 1.0 Context-Length: ''' lisfd = socket.socket(socket.AF_INET,socket.SOCK_STREAM) lisfd.bind((HOST, PORT)) lisfd.listen(2) signal.signal(signal.SIGINT,sigIntHander) runflag = True while runflag: try: confd,addr = lisfd.accept() except socket.error as e: if e.errno == errno.EINTR: print 'get a except EINTR' else: raise continue if runflag == False: break; print "connect by ",addr data = confd.recv(1024) if not data: break print data confd.send(HttpResponse(httpheader,'index.html')) confd.close() else: print 'runflag#',runflag print 'Done'
index.html
Python Server Hello python
Welcom to the python world
测试
测试结果:
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
浏览器
以上是“python如何实现简单http服务器功能”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注创新互联行业资讯频道!