demo web服务器集成解析动态请求的功能

import socket

import re

import multiprocessing

class WSGIServer(object):

    def _init_(self):

        # 1。创建套接字

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

        self.tcp_server_socket.setsockopt(socket.SOL_SOCJET, socket.SOCK_REUSEADDR,1)

        # 2。绑定

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

        # 3。变为监听套接字(最大链接书128)

        self.tcp_server_socket.listen(128)

    def service_client(self,new_socket):

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

    # 1.接收浏览器发送出来的请求,即HTTP请求

    # GET/HTTP/1.1

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

        request_lines = request.splotlines()

        print ('')

        print ('>>>' *30)

        print (request_lines)

    # 新客户端链接

    # GET/index.html HTTP/1.

    # get post put del

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

        file_name = ''

        if ret:

            file_name = ret.group(1)

            print ('*' *50, file_name)

            if file_name == '/':

                file_name = '/index.html'

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

        try:

            f =open('.../Desktop/项目/项目.html', 'rb')

    # f = open('.../Desktop/项目/项目.html' +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

    # response += 'hahaha'

    # f = open('.../Desktop/项目/项目.html','rb')

    # html_content = f.read()

    # f.close()

    # 将Response Header 发送给浏览器

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

    # 将Response Body  发送给浏览器

        new_socket.send(html_content)

    # 关闭客户端套接字

        new_socket.close()

    def main():

        while True:

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

            new_socket, client_addr = tcp_server_socket.accept()

    # 局部变量

    # 5。为这个客户端服务

    # service_client()

            p = multiprocessing.Process(target=service_client,args=(new_socket,))

            p.start()

            new_socket.close()

    # 6。关闭监听套接字

        self.tcp_server_socket.close()

def main():

    #用来完成整体的控制,创建一个web 服务器对象。调用run_forver方法运行

    wsgi_server = WSGIServer()

    wsgi_server.run_forver()

if __name__ =='__main__':

    main()

你可能感兴趣的:(demo web服务器集成解析动态请求的功能)