import json
import re
import socket
import threading
print("server ok http://127.0.0.1:7890")


lubData = [
    {
        "img": "https://ossweb-img.qq.com/upload/adw/image/20210823/bd362a55cd16f5f9acde08cbaba83188.jpeg",
        "title": "9月12日战斗之夜"
    },
    {
        "img": "https://ossweb-img.qq.com/upload/adw/image/20210819/0401ac6137793d1e8ca61c92150c9b7f.jpeg",
        "title": "2021魔女秘宝"
    },
    {
        "img": "https://ossweb-img.qq.com/upload/adw/image/20210813/a57d5aec4562b5076717a1afdcb2d064.jpeg",
        "title": "魔女通行证"
    },
    {
        "img": "https://ossweb-img.qq.com/upload/adw/image/20210824/c4c5dd86352f0768d622a1b8d4256a0d.jpeg",
        "title": "宇宙竞技场"
    },
    {
        "img": "https://ossweb-img.qq.com/upload/adw/image/20210813/c80badfdac1f32a4dd18adaf58519429.jpeg",
        "title": "魔女摇曳 魅惑众生"
    },
]

def service_client(new_socket):
    """为这个客户端返回数据"""

    #  接收浏览器发送过来的请求，即HTTP请求
 
    
    request = new_socket.recv(1024)
    request = request.decode("utf-8")  # 解码
    request_lines = request.splitlines()  # 按照行('\r', '\r\n', \n')分隔，返回一个包含各行作为元素的列表
    print(request_lines)
    # print(len(request_lines))
    # 避免报错
    if len(request_lines) == 0:
        new_socket.close();
        return;

    # 获取请求地址
    ret = re.match(r"[^/]+(/[^ ]*)", request_lines[0])
    #路由
    router = ret.group(1);
    print(router)

    response = "HTTP/1.1 200 NOT FOUND\r\n"
    # 配置跨域
    response += "Access-Control-Allow-Origin: * \r\n"
    # ['Access-Control-Allow-Origin'] = '*'
    # ['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
    # ['Access-Control-Max-Age'] = '1000'
    # ['Access-Control-Allow-Headers'] = '*'
    response += '\r\n'

    if router == "/":
        response += json.dumps({'code': 201, 'data': "你好!我是配彭于晏"})
    elif router == "/xxx":
        response += json.dumps({'code': 200, 'data': "xxx!"})
    elif router == "/dwp":
        response += json.dumps({'code': 200, 'data': "我是最帅的彭于晏!"})
    elif router == "/lbt":
        response += json.dumps({'code': 200, 'data': lubData})
    else:
        response += json.dumps({'code': 404, 'data': router})
    
    # response 返回的数据


    print(response)
    new_socket.send(response.encode("utf-8"))
    new_socket.close()


def main():
    tcp_sever_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    #  服务器先关闭，保证重新开启不占用端口
    tcp_sever_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    tcp_sever_socket.bind(("", 7890))
    tcp_sever_socket.listen(128)
    while True:
        #  等待新客户端的链接
        new_socket, client_addr = tcp_sever_socket.accept()

        # p=multiprocessing.Process(target=service_client,args=(new_socket,))
        p = threading.Thread(target=service_client, args=(new_socket,))
        p.start()
        #  子进程关闭一次主进程还需关闭一次，Linux下文件硬链接的原因，两个名字指向同一个文件，因此要关闭两次
        # new_socket.close()
    #  关闭监听套接字
    tcp_sever_socket.close()


if __name__ == '__main__':
    main()
