httpserver v2.0

httpserver v2.0
io多路复用 和 http训练

from socket import *
from select import *
class HTTPServer:   # 具体功能实现
    def __init__(self, host='0.0.0.0', port=8000, dir=None):
        self.host = host
        self.port = port
        self.dir = dir
        self.address = (host, port)
        self.rlist = []  # 多路复用列表
        self.wlist = []
        self.xlist = []       
        self.create_socket()  # 实例化对象时直接创建套接字
        self.bind() 
    def create_socket(self):     # 创建套接字
        self.sockfd = socket()
        self.sockfd.setsockopt(SOL_SOCKET,SO_REUSEADDR, 1)  
    def bind(self):    # 绑定地址
        self.sockfd.bind(self.address)  
    def serve_forever(self):    # 启动服务
        self.sockfd.listen(3)
        print("Listen the port %d" % self.port)      
        self.rlist.append(self.sockfd)   # IO多路复用接收客户端请求
        while True:
            rs, wx, xs = select(self.rlist,self.wlist,self.xlist)
            for r in rs:
                if r is self.sockfd:
                    c, addr = r.accept()
                    self.rlist.append(c)
                else:                    
                    self.handle(r)  # 处理请求
    def handle(self, connfd):        
        request = connfd.recv(4096)   # 接收HTTP请求       
        if not request:    # 客户端断开
            self.rlist.remove(connfd)
            connfd.close()
            return       
        request_line = request.splitlines()[0]    # 提取请求内容 (字节串按行分割)
        info = request_line.decode().split(' ')[1]
        print(connfd.getpeername(), ':', info)
        if info=='/' or info[-5:]=='.html': #将请求内容分为1,请求网页2,其他
            self.get_html(connfd, info)
        else:
            self.get_data(connfd, info)    
    def get_html(self, connfd, info):  # 返回网页
        if info == '/':            
            filename = self.dir + "/index.html"   # 请求主页
        else:
            filename = self.dir + info
        try:
            fd = open(filename)
        except Exception:    # 网页不存在           
            response = "HTTP/1.1 404 Not Found\r\n"
            response += 'Content-Type:text/html\r\n'
            response += '\r\n'
            response += '

Sorry....

' else: # 网页存在 response = "HTTP/1.1 200 OK\r\n" response += 'Content-Type:text/html\r\n' response += '\r\n' response += fd.read() finally: connfd.send(response.encode()) # 将响应发送给浏览器 def get_data(self, connfd, info): # 其他数据 response = "HTTP/1.1 200 OK\r\n" response += 'Content-Type:text/html\r\n' response += '\r\n' response += "

Waiting for httpserver 3.0

" connfd.send(response.encode()) if __name__ == "__main__": # 用户使用HTTPServer #通过 HTTPServer类快速搭建服务,展示自己的网页 HOST = '0.0.0.0' # 用户决定的参数 PORT = 8000 DIR = './static' # 网页存储位置 httpd = HTTPServer(HOST, PORT, DIR) # 实例化对象 httpd.serve_forever() # 启动服务

你可能感兴趣的:(httpserver v2.0)