web-静态服务器

最近学习了使用基于HTTP协议的协程版的web静态服务器的搭建,这里简单记录下搭建的流程,代码如下:

# -*- coding:utf-8 -*-

from gevent import monkey; monkey.patch_all() #打补丁
import socket,gevent


class WebServer(object):
    def __init__(self):
        self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)

        self.server_socket.bind(('', 8888))

        self.server_socket.listen(128)

    def startup(self):
        #监听多个客户端
        while True:
            new_sock, addr = self.server_socket.accept()
            #使用协程实现
            gevent.spawn(self.handle_client, new_sock)

        self.server_socket.close()


    def handle_client(self,new_sock):
        rev_data = new_sock.recv(4096)
        if rev_data:
            # print("接受到的数据是:%s" % rev_data.decode('utf-8'))
            rev_list = rev_data.decode('utf-8').splitlines()
            file_path = rev_list[0].split(' ')[1]

            if file_path == '/':
                file_name = './html/index.html'
            else:
                file_name = './html'+file_path

            try:
                res_line = 'HTTP/1.1 200 OK\r\n'
                res_headers = 'Connection: Keep-Alive\r\n'
                res_headers += 'Content-Type: text/html; charset=utf-8\r\n\r\n'
                f_read = open(file_name, 'rb')
            except Exception:
                res_line = 'HTTP/1.1 404 Not Found\r\n'
                res_headers = 'Connection: Keep-Alive\r\n'
                res_headers += 'Content-Type: text/html; charset=utf-8\r\n\r\n'
                f_read = open('./html/404.html', 'rb')
                content = f_read.read()
                f_read.close()
            else:
                content = f_read.read()
                f_read.close()
            finally:
                new_sock.send((res_line + res_headers).encode('utf-8') + content)

        else:
            print('已和客户端断开连接!!')

        new_sock.close()

def main():
    '''程序的主入口'''
    # 创建一个web服务器对象
    web_server = WebServer()
    # 启动这个服务器
    web_server.startup()

if __name__ == '__main__':
    main()

你可能感兴趣的:(python)