import socket
import threading
from urllib.parse import urlparse
import sys
import framework
class HttpWebServer(object):
# 创建套接字
def __init__(self):
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(new_socket):
# 接收数据
recv_data = new_socket.recv(4096)
if not recv_data:
new_socket.close()
return
# 解码为utf8
recv_content = recv_data.decode("utf-8")
print(recv_content)
# 解析请求数据
request_lines = recv_content.split("\r\n")
if not request_lines:
new_socket.close()
return
# 解析请求行
request_line = request_lines[0].split(" ")
# 获取请求路径
request_path= request_line[1]
print(request_path)
if request_lines=="/":
request_path = "/index.html"
# 如果请求路径为。html传给web框架处理
if request_path.endswith(".html"):
env = {
"request_path":request_path
}
status,headers,response_body=framework.handle_request(env)
# 返回状态信息
response_line = "HTTP: 1.1 %s/r/n" % status
response_head = ""
for header in headers:
response_head += "%s:%s" % header
reponse_data = (response_line + response_head + "\r\n" + response_body).encode("utf-8")
new_socket.send(reponse_data)
new_socket.close()
else:
try:
with open(f"/home/zzj/Desktop/1/1/{request_path}", "rb") as file:
file_data = file.read()
except FileNotFoundError:
# 文件未找到,返回404 Not Found
response_line = "HTTP/1.1 404 NOT Found\r\n"
response_header = "Server: PWS/1.0\r\n"
path = "/error.html"
with open("/home/zzj/Desktop/1/1/" + path, "rb") as file:
file_data = file.read()
response_body = file_data
response = (response_line + response_header + "\r\n").encode("utf8") + response_body
new_socket.send(response)
else:
# 发送200 OK响应和文件内容
response = "HTTP/1.1 200 OK\r\n\r\n".encode("utf-8") + file_data
new_socket.send(response)
finally:
new_socket.close()
def start(self):
while True:
new_socket, ip_port = self.tcp_server_socket.accept()
sub_thread = threading.Thread(target=self.handle_client_request, args=(new_socket,))
sub_thread.start()
def main():
web_serve=HttpWebServer()
web_serve.start()
if __name__ == '__main__':
main()
Framework
import time
def index():
status = "200 OK"
response_header = [("Server","PWS/1.1")]
data = time.ctime()
return status,response_header,data
def not_found():
status = "200 not found"
response_header = [("Server","PWS/1.1")]
data = "not found"
return status,response_header,data
def handle_request(env):
recive_path = env["request_path"]
print(f"接收的数据:{recive_path}")
if recive_path == "/index.html":
result=index()
return result
else:
result = not_found()
return result