HTTPServer v2.0

主要功能 :

【1】 接收客户端(浏览器)请求

【2】 解析客户端发送的请求

【3】 根据请求组织数据内容

【4】 将数据内容形参http响应格式返回给浏览器

升级点 :

【1】 采用IO并发,可以满足多个客户端同时发起请求情况

【2】 做基本的请求解析,根据具体请求返回具体内容,同时满足客户端简单的非网页请求情况

【3】 通过类接口形式进行功能封装

  1 """
  2 http server 2.0
  3 io多路复用 http 练习
  4 
  5 思路分析:
  6 1. 使用类进行封装
  7 2. 从用户使用角度决定类的编写
  8 """
  9 from socket import *
 10 from select import select
 11 
 12 
 13 #  具体HTTP sever功能
 14 class HTTPServer:
 15   def __init__(self, host, port, dir):
 16     #  添加属性
 17     self.address = (host, port)
 18     self.host = host
 19     self.port = port
 20     self.dir = dir
 21     self.rlist = []
 22     self.wlist = []
 23     self.xlist = []
 24     self.create_socket()
 25     self.bind()
 26 
 27   # 创建套接字
 28   def create_socket(self):
 29     self.sockfd = socket()
 30     self.sockfd.setsockopt(SOL_SOCKET,
 31                            SO_REUSEADDR, 1)
 32 
 33   def bind(self):
 34     self.sockfd.bind(self.address)
 35 
 36   #  启动服务
 37   def serve_forever(self):
 38     self.sockfd.listen(5)
 39     print("Listen the port %d" % self.port)
 40     self.rlist.append(self.sockfd)
 41     while True:
 42       rs, ws, xs = select(self.rlist, self.wlist,
 43                           self.xlist)
 44       for r in rs:
 45         if r is self.sockfd:
 46           c, addr = r.accept()
 47           print("Connect from", addr)
 48           self.rlist.append(c)
 49         else:
 50           #  处理请求
 51           self.handle(r)
 52 
 53   # 具体处理请求
 54   def handle(self, connfd):
 55     #  接收http请求
 56     request = connfd.recv(4096)
 57     #  防止客户端断开
 58     if not request:
 59       self.rlist.remove(connfd)
 60       connfd.close()
 61       return
 62 
 63     # 提取请求内容
 64     request_line = request.splitlines()[0]
 65     info = request_line.decode().split(' ')[1]
 66     print(connfd.getpeername(), ":", info)
 67 
 68     #  info分为访问网页或者其他内容
 69     if info == '/' or info[-5:] == '.html':
 70       self.get_html(connfd, info)
 71     else:
 72       self.get_data(connfd, info)
 73 
 74   # 处理网页请求
 75   def get_html(self, connfd, info):
 76     if info == '/':
 77       filename = self.dir + "/index.html"
 78     else:
 79       filename = self.dir + info
 80     try:
 81       fd = open(filename)
 82     except Exception:
 83       #  没有网页
 84       responseHeaders = "HTTP/1.1 404 Not Found\r\n"
 85       responseHeaders += '\r\n'
 86       responseBody = "Sorry,Not found the page"
 87     else:
 88       #  存在网页
 89       responseHeaders = "HTTP/1.1 200 OK\r\n"
 90       responseHeaders += '\r\n'
 91       responseBody = fd.read()
 92     finally:
 93       response = responseHeaders + responseBody
 94       connfd.send(response.encode())
 95 
 96   def get_data(self, connfd, info):
 97     responseHeaders = "HTTP/1.1 200 OK\r\n"
 98     responseHeaders += '\r\n'
 99     responseBody = "Waiting for httpserver 3.0"
100     response = responseHeaders + responseBody
101     connfd.send(response.encode())
102 
103 if __name__ == "__main__":
104   """
105   希望通过HTTPServer类快速搭建http服务
106  用以展示自己的网页
107   """
108 
109   # 用户自己决定的内容
110   HOST = '0.0.0.0'
111   PORT = 8000
112   DIR = "./static"  # 网页存储位置
113 
114   httpd = HTTPServer(HOST, PORT, DIR)  # 实例化对象
115   httpd.serve_forever()  # 启动http服务
http server 2.0

猜你喜欢

转载自www.cnblogs.com/maplethefox/p/11056054.html