A simple web framework
The overall process is very simple, browser and enter 127.0.0.1:8000, return html, html because there css, js, the browser will default to test.css, test.js add 127.0.0.1 to access, because HTTP is a short link Once 127.0.0.1:8000 complete the request response, splicing will immediately test.html in test.css, test.js visit.
import socket sk = socket.socket() sk.bind(("127.0.0.1",8000)) sk.listen() while 1: conn,addr = sk.accept() from_client_msg = conn.recv(1024) # print(from_client_msg.decode("utf-8").split(" ")) #以空格分开看清每部分内容 url = from_client_msg.decode("utf-8").split(" ")[1] if url == "/": #Browser input http://127.0.0.1:8000, the server resulting url is "/", because the browser's default at the end of supplement "/" with Open ( " test.html " , " rb " ) AS f: conn.send (B " the HTTP / 1.1 200 is the OK \ R & lt \ n-\ R & lt \ n- " ) conn.send (reached, f.read ()) conn.Close () elif URL == " /test.css " : with Open ( " test.css " , " RB " ) AS F: conn.send (B " the HTTP / 1.1 200 is the OK \ R & lt \ n-\ R & lt \ n- ") conn.send(f.read()) conn.close() elif url == "/test.js": with open("test.js","rb") as f: conn.send(b"HTTP/1.1 200 OK \r\n\r\n") conn.send(f.read()) conn.close() sk.close()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="test.css"> <script src="test.js"></script> </head> <body> <h1>你好啊</h1> </body> </html>
h1{ background-color: red; }
alert("hello!");