code:
from multiprocessing import Process import re import socket HTML_ROOT_DIR = "./html" class HTTPServer(object): """服务器""" def __init__(self): self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) def start(self): """开启服务器""" self.server_socket.listen(128) while True: client_socket, client_addr = self.server_socket.accept() print("[%s, %s]用户连接上了..." % client_addr) handle_client_process = Process(target=self.handle_client, args=(client_socket,)) handle_client_process.start() client_socket.close() def handle_client(self, client_socket): """处理客户端请求""" request_data = client_socket.recv(1024) print("request_data: ", request_data) request_lines = request_data.splitlines() for line in request_lines: print(line) request_start_line = request_lines[0] file_name = re.match(r"w+ +(/[^ ]*) ", request_start_line.decode("utf-8")).group(1) print("file_name ==" ,file_name) if "/" == file_name: file_name = "/index.html" print("HTML_ROOT_DIR + file_name = ",HTML_ROOT_DIR + file_name) try: file = open(HTML_ROOT_DIR + file_name, "rb") except IOError: # 设置响应头 response_start_line = "HTTP/1.1 404 Not Fount " response_head_line = "server: My server " response_body = "The File is not Found!" else: file_data = file.read() file.close() # 设置响应头 response_start_line = "HTTP/1.1 200 OK " response_head_line = "Server: My server " response_body = file_data.decode("utf-8") finally: response = response_start_line + response_head_line + " " + response_body print("response data: ", response) client_socket.send(bytes(response, "utf-8")) client_socket.close() def bind(self, port): self.server_socket.bind(("127.0.0.1", port)) def main(): http_server = HTTPServer() http_server.bind(9000) http_server.start() if __name__ == "__main__": main()