Web静态服务器-显示需要的页面

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

import socket
import re


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

    # 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_headers = "HTTP/1.1 200 OK\r\n"
        response_headers += "\r\n"
        response_body = f.read()
        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)

while True:
    # 接收消息
    new_socket, addr = tcp_server_socket.accept()

    service_client(new_socket)
上一篇下一篇

猜你喜欢

热点阅读