Python Web服务器案例

from  multiprocessing import  Process

import socket

import re

HTML_ROOT_DIR = './html'

def handleClient(client):

    #读取客户端请求数据
    request_data =  client.recv(1024)

    request_data_list =  request_data.splitlines()

    httpRequestMethodLine = request_data_list[0]

    httpRequestMethodLine =  httpRequestMethodLine.decode('utf-8')

    try:
        ret  = re.match(r'\w*\s+(/[^\s]*)\s+',httpRequestMethodLine)

    except AttributeError:

        print('not match!')

    else:

        sub_dir = ret.group(1)

        if sub_dir == '/':
            sub_dir = '/index.html'

        path = HTML_ROOT_DIR + sub_dir

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

        response_headers = 'Server:My server\r\n'

        try:
            file = open(path)

        except FileNotFoundError:

            response_body = '\r\n' + '找不到该资源'

            response = response_start_line + response_headers + response_body

        else:

            html = file.read()

            response_body = '\r\n' + str(html)

            response = response_start_line + response_headers + response_body

            file.close()

        finally:

            client.send(bytes(response, 'utf-8'))

            client.close()


def main():

        # 创建服务器
        webServer = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        #设置socket选项,地址以及端口可复用
        webServer.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)

        webServer.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)

        # 判定端口号
        webServer.bind(('127.0.0.1', 9000))

        # 开始监听
        webServer.listen()

        while True:

            # 接收客户端
            client, addressInfo = webServer.accept()

            # 创建进程,单独执行客户端任务
            client_process = Process(target=handleClient, args=(client,))

            client_process.start()

            client.close()




if __name__ == '__main__':

    main()


你可能感兴趣的:(Python Web服务器案例)