import socket
import threading
# 把提供服务的Web服务器抽象成一个类(HTTPWebServer)
class HTTPWebServer(object):
# 提供Web服务器的初始化方法,在初始化方法里面创建socket对象
def __init__(self):
# 创建服务端tcp socket对象
tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 程序退出端口号立即释放
tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
# 绑定端口号
tcp_server_socket.bind(("", 9090))
# 设置监听
tcp_server_socket.listen(128)
self.tcp_server_socket = tcp_server_socket
# 处理客户端的请求
@staticmethod
def handle_client_request(conn_socket):
# 2. 获取浏览器发送的http请求报文数据
client_request_data = conn_socket.recv(4096)
# 对二进制数据进行解码
client_request_content = client_request_data.decode("utf-8")
print(client_request_content)
# 获取用户请求资源的路径
request_list = client_request_content.split(" ", maxsplit=2)
print(request_list)
print(len(request_list))
if len(request_list) != 3:
conn_socket.close()
return
# 获取请求资源路径
request_path = request_list[1]
if request_path == "/":
request_path = "/index.html"
try:
# 根据请求资源的路径,读取请求指定文件的数据
with open("static" + request_path, "rb") as file:
file_data = file.read()
except Exception as e:
# 判断请求的文件在服务端不存在,组装404状态的响应报文,发送给浏览器
# 组装404响应报文数据
# 响应行
response_line = "HTTP/1.1 404 Not Found\r\n"
# 响应头
response_header = "Server: PWB/1.0\r\nContent-Type: text/html;charset=utf-8\r\n"
# 响应体
response_body = "<h1>非常抱歉,您当前访问的网页已经不存在了。</h1>"
# 3. 读取固定页面数据,把页面数据组装成HTTP响应报文数据发送给浏览器。
response_data = (response_line + response_header + "\r\n" + response_body).encode("utf-8")