05 返回静态文件的多线程web框架
05 返回静态文件的多线程web框架
服务器server端python程序(多线程版):
1 import socket 2 3 from threading import Thread,currentThread,activeCount,enumerate 4 5 server = socket.socket() 6 7 server.bind(("127.0.0.1", 8888)) 8 9 server.listen() 10 11 def func_html(conn): 12 13 print("html>>>",currentThread()) 14 15 with open("index.html", "rb")as f: 16 17 conn.send(f.read()) 18 19 def func_js(conn): 20 21 print("js>>>", currentThread()) 22 23 with open("index.js", "rb")as f: 24 25 conn.send(f.read()) 26 27 28 29 def func_css(conn): 30 31 print("css>>>", currentThread()) 32 33 with open("index.css", "rb")as f: 34 35 conn.send(f.read()) 36 37 38 39 def func_img(conn): 40 41 print("img>>>", currentThread()) 42 43 with open("index.png", "rb")as f: 44 45 conn.send(f.read()) 46 47 48 49 def func_ico(conn): 50 51 print("icon>>>", currentThread()) 52 53 with open("favicon.ico","rb")as f: 54 55 conn.send(f.read()) 56 57 58 59 def respones_back(conn,path): 60 61 conn.send("HTTP/1.1 200 ok \r\n\r\n".encode("utf-8")) 62 63 if path == "/": 64 65 func_html(conn) 66 67 elif path == "/index.js": 68 69 func_js(conn) 70 71 elif path == "/index.css": 72 73 func_css(conn) 74 75 elif path == "/index.png": 76 77 func_img(conn) 78 79 elif path == "/favicon.ico": 80 81 func_ico(conn) 82 83 conn.close() 84 85 86 87 if __name__ == '__main__': 88 89 while 1: 90 91 conn, client_addr = server.accept() 92 93 http_request=conn.recv(1024).decode("utf-8") 94 95 path=http_request.split("\r\n")[0].split(" ")[1] 96 97 print("path>>>",path) 98 99 # respone_back(path) 100 101 #开线程进行异步处理 102 103 task=Thread(target=respones_back,args=(conn,path)) 104 105 task.start() 106 107 # print("threads>>>",activeCount(),enumerate()) #查看当前存活的线程和数量
客户端浏览器访问:
在浏览器地址栏直接输入地址端口:127.0.0.1:8888
index.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="index.css"> <link rel="icon" href="favicon.ico"> <title>多线程版</title> </head> <body> <div id="d1"> <h1>多线程版的页面:本html页面引用了外部本地css样式和js代码(本地图片)</h1> </div> <img src="index.png" alt="本地图片" title="本地图片"> </body> <script src="index.js"></script> </html>