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 += '<h1>Sorry....</h1>'
        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 += "<h1>Waiting for httpserver 3.0</h1>"
        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()  # 启动服务

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • lucy书阅读 143评论 0 0
  • 函数 函数头部始终以关键字def开始,表示这是函数定义。 然后是函数名称,遵循的是和变量一样的命名规范。 名称之后...
    谁共我醉明月阅读 145评论 1 0
  • 我有三个室友,一个永远不在寝室,一个天天各种忙,还有一个,是军嫂。 她叫小花,长发齐刘海,人瘦也漂亮,能缝衣服,会...
    戌时何时归来阅读 587评论 6 6
  • “大姨妈”这个称呼每个女性朋友都很熟悉,每个月都要来这么一次,有时候还会出现异常的疼痛感,这种叫做痛经。痛经其实也...
    月季舒阅读 440评论 0 0