本篇文章主要介绍了python实现简单的httpserver服务器示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
要写一个类似tomcat的简易服务器,首先需弄清楚这几点:
1. 客户端(client)和服务端(server)的角色及作用
角色a向角色b请求数据,这时可以把a视为客户端,b视为服务端。客户端的主要职责是发送请求和接收服务端根据自己发送的请求返回的请求信息,而服务端的主要职责是接收请求和返回请求数据。
2. 浏览器是什么及工作原理
我们常说b/s,c/s架构,所谓的b/s指browser/server,c/s指client/server,b/s架构其实就是应用于浏览器的程序,只要最后在浏览器上展现的都是 b/s架构,而非在浏览器上展现的都是c/s架构,如常见的英雄联盟游戏。但是本质上只有c/s架构,因为浏览器是一种特殊的客户端。
浏览器的特殊之处是有一下三大引擎:
dom解析引擎:即浏览器可以解析html
样式解析引擎:即浏览器可以解析css
脚本解析引擎:即浏览器可以解析javascript
3. socket
上面提到的客户端服务端,他们之间是怎样实现连接及数据传递的,这就是socket,每一门编程语言都有socket编程,socket的作用就是提供了网络通信的能力
4. http协议及http与tcp/tp的区别
客户端和服务端通过socket实现了网络通信的能力,可以实现数据传递。而协议是规范数据传输,也就是说客户端和服务端之间传输数据要按照一定得规范和标准传输,不能瞎传。
tcp/ip(transmission control protocol/internet protocol):传输控制协议/网间协议
http(hypertext transfer protocol):超文本传输协议。
tcp/tp的区别:
做一个形象的比喻,tcp/tp是马路,http则是马路上的汽车,所以http一定是在tcp/tp的基础上的。
http主要是应用在web程序上,设计之初就是为了提供一种发布和接收html页面的方法,这样说可能很抽象很难理解。具体的说当我们去访问一个网站时,只需要拿到基于这个网站的内容(比如html,css,javascript)。但我们抓取浏览器接收到的资源包(可以用fiddler工具)发现除了网页需要的实体内容还有一些下面信息:
http/1.1 200 ok
cache-control: private
content-type: text/plain; charset=utf-8
content-encoding: gzip
vary: accept-encoding
server: microsoft-iis/7.5
x-aspnet-version: 4.0.30319
x-powered-by: asp.net
date: tue, 24 jan 2017 03:25:23 gmt
connection: close
content-length: 661
这就是http协议规范,比如content-type就是说传输的时候文件的格式,content-encoding规定了编码格式。不止以上这些,非常多,关于这些参数含义这里就不去一一介绍
5. url的含义
url(统一资源定位符),就是我们常说的网址,直接来解析一个url来说明他:http://198.2.17.25:8080/webapp/index.html
这个含义是找到ip为198.2.17.25的服务器下目录为webapp的index.html
但是我们常看到的是这样的url:http://goodcandle.cnblogs.com/archive/2005/12/10/294652.aspx
其实这个和上面的一样,不过这里存在一个域名解析,可以将goodcandle.cnblogs.com解析成对应的ip地址
弄清楚以上五点之后开始来写代码
webserver.py
import socket
import sys
import getfilecontent
#声明一个将要绑定的ip和端口,这里是用本地地址
server_address = ('localhost', 8080)
class webserver():
def run(self):
print >>sys.stderr, 'starting up on %s port %s' % server_address
#实例化一个socket
sock=socket.socket(socket.af_inet,socket.sock_stream)
#绑定ip和端口
sock.bind(server_address)
#设置监听
sock.listen(1)
#这里首先给个死循环,其实这里是需要多线程的,再后续版本将会实现
while true:
#接受客户端的请求并得到请求信息和请求的端口信息
connection, client_address = sock.accept()
print >>sys.stderr, 'waiting for a connection'
try:
#获取请求信息
data = connection.recv(1024)
if data:
#发送请求信息
connection.sendall(getfilecontent.gethtmlfile(data))
finally:
connection.close()
if __name__ == '__main__':
server=webserver()
server.run()
webserver.py很清晰简洁,connection.sendall()服务端返回信息给浏览器,但是发送的数据必须遵循http协议规范
getfilecontent.py是对发送的数据进行http协议规范处理
import sys
import os
#得到要发送的数据信息
def gethtmlfile(data):
msgsendtoclient=""
requesttype=data[0:data.find("/")].rstrip()
#判断是get请求还是post请求
if requesttype=="get":
msgsendtoclient=responsegetrequest(data,msgsendtoclient)
if requesttype=="post":
msgsendtoclient=responsepostrequest(data,msgsendtoclient)
return msgsendtoclient
#打开文件,这里不直接写,二是去取要发送的文件再写
def getfile(msgsendtoclient,file):
for line in file:
msgsendtoclient+=line
return msgsendtoclient
#筛选出请求的一个方法
def getmidstr(data,startstr,endstr):
startindex = data.index(startstr)
if startindex>=0:
startindex += len(startstr)
endindex = data.index(endstr)
return data[startindex:endindex]
#获取要发送数据的大小,根据http协议规范,要提前指定发送的实体内容的大小
def getfilesize(fileobject):
fileobject.seek(0,2)
size = fileobject.tell()
return size
#设置编码格式和文件类型
def setparaandcontext(msgsendtoclient,type,file,openfiletype):
msgsendtoclient+="content-type: "+type+";charset=utf-8"
msgsendtoclient+="content-length: "+str(getfilesize(open(file,"r")))+"\n"+"\n"
htmlfile=open(file,openfiletype)
msgsendtoclient=getfile(msgsendtoclient,htmlfile)
return msgsendtoclient
#get请求的返回数据
def responsegetrequest(data,msgsendtoclient):
return responserequest(getmidstr(data,'get /','http/1.1'),msgsendtoclient)
#post请求的返回数据
def responsepostrequest(data,msgsendtoclient):
return responserequest(getmidstr(data,'post /','http/1.1'),msgsendtoclient)
#请求返回数据
def responserequest(getrequestpath,msgsendtoclient):
headfile=open("head.txt","r")
msgsendtoclient=getfile(msgsendtoclient,headfile)
if getrequestpath==" ":
msgsendtoclient=setparaandcontext(msgsendtoclient,"text/html","index.html","r")
else:
rootpath=getrequestpath
if os.path.exists(rootpath) and os.path.isfile(rootpath):
if ".html" in rootpath:
msgsendtoclient=setparaandcontext(msgsendtoclient,"text/html",rootpath,"r")
if ".css" in rootpath:
msgsendtoclient=setparaandcontext(msgsendtoclient,"text/css",rootpath,"r")
if ".js" in rootpath:
msgsendtoclient=setparaandcontext(msgsendtoclient,"application/x-javascript",rootpath,"r")
if ".gif" in rootpath:
msgsendtoclient=setparaandcontext(msgsendtoclient,"image/gif",rootpath,"rb")
if ".doc" in rootpath:
msgsendtoclient=setparaandcontext(msgsendtoclient,"application/msword",rootpath,"rb")
if ".mp4" in rootpath:
msgsendtoclient=setparaandcontext(msgsendtoclient,"video/mpeg4",rootpath,"rb")
else:
msgsendtoclient=setparaandcontext(msgsendtoclient,"application/x-javascript","file.js","r")
return msgsendtoclient
以上就是python实现简单的httpserver服务器的详细内容。