多进程web_server

import socket

import re

import multiprocessing

class WSGIServer():

    def __init__(self):

        # 1.创建套接字

        self.tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        self.tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        # 2.绑定

        self.tcp_server_socket.bind(('', 7890))

        # 3.变为监听套接字

        self.tcp_server_socket.listen(128)

    def server_client(self,new_socket):

        '''为这个客户端返回数据'''

        # 1、接收浏览器发过来的请求,即Http请求

        # GET / HTTP/1.1

        request = new_socket.recv(1024).decode('utf-8')

        request_lines = request.splitlines()

        print('')

        print('>>'*20)

        print(request_lines)

        ret = re.match(r'[^/]+(/[^ ]*)',request_lines[0])

        file_name = ''

        if ret:

            file_name = ret.group(1)

            print('*'*50,file_name)

            if file_name == '/':

                file_name = '/丝芙兰.html'

        # 2、返回HTTP格式的数据给浏览器

        try:

            f = open('../sephore'+ file_name,'rb')

        except:

            response = 'HTTP/1.1 404 NOT FOUND\r\n'

            response += '\r\n'

            response += '---FILE NOT FOUND---'

            new_socket.send(response.encode('utf-8'))

        else:

            html_content = f.read()

            f.close()

            # 2.1 准备发送给浏览器的Header

            response = 'HTTP/1.1 200 OK\r\n'

            response += '\r\n'

            #2.2 准备发给浏览器的Body

            new_socket.send(response.encode('utf-8'))

            new_socket.send(html_content)

        # 关闭客户端套接字

        new_socket.close()

    def run_forever(self):

        while True:

            # 4、等待新客户端的链接

            new_socket, client_addr = self.tcp_server_socket.accept()

            # 5 、为这个客户端服务

            p = multiprocessing.Process(target=self.server_client,args=(new_socket,))

            p.start()

            new_socket.close()

        # 6、关闭监听套接字

        self.tcp_server_socket.close()

def main():

    '''完成整体控制,创建一个web服务器对象,调用run_forever方法运行'''

    wsgi_server = WSGIServer()

    wsgi_server.run_forever()

if __name__ == '__main__':

    main()

你可能感兴趣的:(多进程web_server)