背景
写一个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
<html> <head> <title>Python Server</title> </head> <body> <h1>Hello python</h1> <p>Welcom to the python world</br> </body> </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
浏览器
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
标签:
python,http,服务器
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
暂无“python实现简单http服务器功能”评论...
更新动态
2024年05月03日
2024年05月03日
- [7504]ReferenceSoundEdition-GreatGuitarTunes(2013)[GermanyHQCD]
- 刘嘉佳《往日时光HQ》头版限量[低速原抓WAV+CUE]
- 单依纯《纯情歌》开盘母带[低速原抓WAV+CUE]
- 杨乐婷《遥望HQ》头版限量编号[低速原抓WAV+CUE]
- 蔡琴《三十周年纪念版》6N纯银镀膜[正版CD低速原抓WAV+CUE][519M]
- 张学友《昨夜梦魂中》[FLAC][453M]
- 群星《17号音乐仓库2 第9期》[320K/MP3][150.23MB]
- 汤兰花.2000-一代佳人(环球唱片金曲系列风华再现)【WAV+CUE】
- 罗美玲.2005-生日领悟(EP)【华研国际】【WAV+CUE】
- 李佳薇《相反的是》WAV
- 试音碟《金指妙弹电子琴演奏》5CD[WAV]
- 【新世纪电子】Авирадж2023-ИллюзияОбмана(FLAC)
- 陈婧霏.2024-春色(EP)【有此山文化】【FLAC分轨】
- 郭富城.2000-无忌VS未来(EP)【华纳】【WAV+CUE】
- 群星.2003-追忆林振强3CD【华纳】【WAV+CUE】