Web静态服务器-非堵塞模式

2020-03-12  本文已影响0人  GaoYuan117
# -*- coding:utf-8 -*-
# Author GaoYuan

import socket


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

    # 1.接收浏览器发过来的请求。即http请求
    global response_headers, response_body

    # request = client_socket.recv(1024).decode("utf-8")
    # print(request)

    # 按行切割获取的信息,拿到地址 GET /classic.css HTTP/1.1
    # 处理多个请求
    lines = request.splitlines()

    # 正则匹配出来需要读取的文件 /classic.css
    # result = re.match(r"[^/]*([^ ]*)", splits[0])
    # print("*" * 20, result.group(1))

    # 分割出需要读取的文件名字。GET /classic.css HTTP/1.1 ---->  /classic.css
    if len(lines) <= 0:
        return

    splits = lines[0].split(" ")

    file_name = splits[1]
    if file_name == "/":
        file_name = "index.html"

    print("*" * 20, splits[1])

    # 2.读取文件内容,返回http格式的数据,给浏览器
    try:
        f = open("./html/" + file_name, "rb")
    except:
        # 404
        response_headers = "HTTP/1.1 404 NOT FOUND\r\n"
        response_headers += "\r\n"
        response_body = "file not found".encode("utf-8")

    else:
        response_body = f.read()

        response_headers = "HTTP/1.1 200 OK\r\n"
        #  长链接:通知服务器 应接收的数据是多大
        response_headers += "Content-Length:%d\r\n" % len(response_body)
        response_headers += "\r\n"
        f.close()
    finally:
        # 发送请求头
        client_socket.send(response_headers.encode("utf-8"))
        # 发送请求体
        client_socket.send(response_body)

    # 关闭套接字
    # client_socket.close()


# 创建套接字
tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 设置当服务器先close 即服务器端4次挥手之后资源能够立即释放,这样就保证了,下次运行程序时 可以立即绑定7788端口
tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

# 绑定地址
tcp_server_socket.bind(("", 9099))

# 变为监听套接字
tcp_server_socket.listen(128)

# 将套接字变为非阻塞
tcp_server_socket.setblocking(False)


client_socket_list = list()

while True:
    # 接收消息
    try:
        new_socket, addr = tcp_server_socket.accept()
    except Exception as ret:
        pass
    else:
        new_socket.setblocking(False)
        client_socket_list.append(new_socket)

    for client_socket in client_socket_list:
        try:
            recv_data = client_socket.recv(1024).decode("utf-8")
        except:
            pass
        else:
            if recv_data:
                service_client(client_socket, recv_data)
            else:
                client_socket.close()
                client_socket_list.remove(client_socket)
上一篇下一篇

猜你喜欢

热点阅读