Python实现简单http服务器
程序员文章站
2024-01-27 10:00:34
写一个python脚本,实现简单的http服务器功能:
1.浏览器中输入网站地址:172.20.52.163:20014
2.server接到浏览器的请求后,读取本地的...
写一个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
浏览器
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。