这段代码简单的描述了一个web服务器框架 这个框架由三部分组成
第一个文件代码:
import socket,multiprocessing,re
class HTTPServer():
def __init__(self,prot):
self.sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.bind(("",prot))
def start(self):
"""开始创建链接收发数据"""
self.sock.listen(128)
while True:
#创建一个连接
user_name,user_ip = self.sock.accept()
user_process = multiprocessing.Process(target=self.hand_clien,args=(user_name,))
user_process.start()
user_name.close()
def start_response(self,status,headers):
response_headers = "HTTP/1.1 " + status + "\n"
for lin in headers:
response_headers += "%s: %s"%lin
self.response_headers = response_headers
def hand_clien(self,user_name):
"""拿到请求的数据"""
#存在一个bug 这个bug是当进程其中一个被销毁另一个再去拿数据就会报错
user_data = user_name.recv(1024).decode('utf-8')
request_date = user_data.splitlines()
request_date_startline = request_date[0]
#提取用户要搜索的名字
file_neme = re.match(r"\w+ +(/[^ ]*)",request_date_startline).group(1)
method = re.match(r"(\w+) +/[^ ]* ", request_date_startline).group(1)
if file_neme.endswith(".py"):
#给出py文件的内容
try:
m = __import__(file_neme[1:-3])
except Exception:
self.response_headers = "HTTP/1.1 404 Not Found\n"
response_body = "not found"
else:
env = {
"PATH_INFO": file_neme,
"METHOD": method
}
response_body = m.application(env,self.start_response)
response = self.response_headers + "\n\n" + response_body
print(response)
else:
if '/' == file_neme:
file_neme = 'Hello.html'
try:
file = open(file_neme,"r")
except Exception:
response_start_line = "HTTP/1.1 404 Not Found\r\n"
response_headers = "Server: My server\r\n"
response_body = "The file is not found!"
else:
file_data = file.read()
file.close()
response_start_line = "HTTP/1.1 200 OK\r\n"
response_headers = "Server: My server\r\n\r\n"
response_body = file_data
response = response_start_line + response_headers + "\r\n" + response_body
user_name.send(response.encode('utf-8'))
user_name.close()
def main():
httpserver = HTTPServer(7878)
httpserver.start()
if __name__ == '__main__':
main()
第二个.py文件代码:
import time:
def application(evn,start_respones):
state = '200 OK'
headers = [
("Content-Type", "text/plain")
]
start_respones(state,headers)
return time.ctime()
第三个 .html文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>nihao</title>
</head>
<body>
hello world!
</body>
</html>
最后两个文件为附属文件 当浏览器访问的是 /*.py的时候就会输出.py文件的内容 如果只有IP地址端口号就是访问主页html文件
注意:
返回给客户端(浏览器)的时候需要严格按照格式进行:
第一行返回是状态后面跟换行符
第二行是header说明是什么文本 必须是键值对的形式然后换行符 后面再跟一个换行符
第三行是body 就是网页的内容