🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
#### 服务器代码 ~~~ #! /usr/bin/env python # -*- coding:utf-8 -*- ''' @Time: 5/1/187:55 PM @Author:haibo @File: MyWebServer.py ''' import socket import re import sys from multiprocessing import Process # 定义常量,所有字母全部大写,设置静态文件根目录 HTML_ROOT_DIR = "./wwwroot" WSGI_ROOT_DIR = "./wsgipython" class HTTPServer(object): '''''' def __init__(self, application): '''构造函数,application:框架的的application''' # 导入框架对象 self.app = application # 创建socket套接字 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循环 while True: client_socket, client_adress = self.server_socket.accept() print("[%s,%s]" % (client_adress[0], client_adress[1])) handle_process = Process(target=self.handle_client, args=(client_socket,)) handle_process.start() client_socket.close() def start_response(self, status, headers): ''' status = headers = [ ("Content-Type", "text/plain") ] ''' # 框架内的status,header 重组新的报文头部 response_headers = "HTTP/1.1 " + status + "\r\n" for header in headers: response_headers += "%s:%s\r\n" % header self.response_headers = response_headers def handle_client(self, client_socket): # 获取客户端请求 request_data = client_socket.recv(1024) # print("*1" * 20) # print("request_data:", request_data) # 获取请求报文,按照(\r\n)分割,返回列表 request_lines = request_data.splitlines() # for line in request_lines: # print(line) # 解析请求报文 # "GET / HTTP/1.1" request_start_line = request_lines[0] # re.match(r"\w+\s+(/[^\s]*)\s", request_start_line) # 提取用户请求的文件名字 file_name = re.match(r"\w+ +(/[^ ]*) ", request_start_line.decode("utf-8")).group(1) # method = re.match(r"\w+ +/[^ ]* ", request_start_line.decode("utf-8")).group(1) env = { "PATH_INFO": file_name, # "METHOD": method } # 获取报文body,框架中返回了body response_body = self.app(env, self.start_response) response = self.response_headers + '\r\n' + response_body # print("*3" * 20) # print("response data:", response) client_socket.send(bytes(response, "utf-8")) client_socket.close() def bind(self, port): self.server_socket.bind(("", port)) def main(): sys.path.insert(1, WSGI_ROOT_DIR) if len(sys.argv) < 2: sys.exit("python3 MyWebServer.py Moudle:app") # python MyWebServer.py MyWebFramework:Application modle_name, app_name = sys.argv[1].split(":") m = __import__(modle_name) app = getattr(m, app_name) # app = Application() http_server = HTTPServer(app) http_server.bind(8001) http_server.start() if __name__ == '__main__': main() ~~~