• httpserver


    from socket import *
    from threading import Thread
    import sys
    import traceback
    
    #httpserver类,封装具体的服务器功能
    class HTTPServer(object):
        def __init__(self, server_addr, static_dir):
            #增加服务器对象属性
            self.server_address = server_addr
            self.static_dir = static_dir
            self.ip = server_addr[0]
            self.port = server_addr[1]
            #创建套接字
            self.create_socket()
    
        def create_socket(self):
            self.sockfd = socket()
            self.sockfd.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
            self.sockfd.bind(self.server_address)
    
    
        #设置监听等待客户端连接
        def serve_forever(self):
            self.sockfd.listen(5)
            print("Listen the port %d" % self.port)
            while True:
                try:
                    connfd,addr = self.sockfd.accept()
                except KeyboardInterrupt:
                    self.sockfd.close()
                    sys.exit("服务器退出")
                except Exception:
                    traceback.print_exc()
                    continue
                #创建新的线程处理请求
                clientThread = Thread(target = self.handleRequset, args = (connfd,))
                clientThread.daemon = True
                clientThread.start()
    
        #客户端请求函数
        def handleRequset(self, connfd):
            #接收客户端请求
            request = connfd.recv(4096)
            #解析请求内容
            requestHeaders = request.splitlines()
            print(connfd.getpeername(),":", requestHeaders[0])
    
            #获取具体请求内容
            getRequest = str(requestHeaders[0]).split(" ")[1]
    
            if getRequest == "/" or getRequest[-5:] == ".html":
                self.get_html(connfd , getRequest)
            else:
                self.get_data(connfd, getRequest)
            connfd.close()    #这个是一定要的,要不然就会显示不出内容
    
        def get_data(self, connfd, getRequest):
            urls = ['/time', '/tedu', '/python']
            if getRequest in urls:
                response = "HTTP/1.1 200 OK
    "
                response += "
    "
                if getRequest == "/time":
                    import time
                    responseBody = time.ctime()
                elif getRequest == "/tedu":
                    responseBody = "Welcome to tedu"
                elif getRequest == "/python":
                    responseBody = "人生苦短,我用python"
            else:
                response = "HTTP/1.1 404 not found
    "
                response += "
    "
                responseBody = "======Sorry not found===="
                print("3333")
    
            response = response + responseBody
            connfd.send(response.encode())
    
    
    
        def get_html(self, connfd, getRequest):
            if getRequest == "/":
                filename = self.static_dir + "/index.html"
            else:
                filename = self.static_dir + getRequest
            try:
                f = open(filename)
            except Exception as e:
                #没有找到页面
                response = "HTTP/1.1 404 not found
    "
                response += "
    "
                responseBody = "======Sorry not found===="
                print(e)
            else:
                print("!!!!!")
                response = "HTTP/1.1 200 OK
    "
                response += "
    "
                responseBody = f.read()
            finally:
                response = response + responseBody
                connfd.send(response.encode())
    
    if __name__ == "__main__":
        #服务器IP
        server_addr = ("0.0.0.0", 8000)
        #我的静态页面存储目录
        static_dir = "./static"
    
        #生成对象
        httpd = HTTPServer(server_addr, static_dir)
    
        #启动服务器
        httpd.serve_forever()
  • 相关阅读:
    2008年Web2.0峰会:发展是绝对的硬道理
    盖茨"接班人":微软产品为何总是挨批
    如何使用命令方式检测mx记录是否生效
    IBM公布未来5年将改变人类生活的五大科技
    谷歌李开复:我的传奇人生源于十句箴言
    VCL已死,RAD已死(3)
    VCL已死,RAD已死(2)
    主要程序设计语言范型综论与概要
    谷歌正式放弃与雅虎的广告合作计划
    模仿google分页代码
  • 原文地址:https://www.cnblogs.com/zengsf/p/9664685.html
Copyright © 2020-2023  润新知