- 在目录下拥有一个文件夹保存了静态网页 ./static
- 在目录下拥有一个文件夹保存了动态网页 ./templates
- 对请求资源不正确的做出错误处理,返回状态号 404 Not Found
- while True : 上一个客户断开后,可以接受新的客户连接
- 发送完报文后要关闭与客户端建立的套接字连接
- 三层装饰器的作用是建立一个字典的关系,字典名[请求的网址]=本地资源
import socket
class WebServer():
def __init__(self):
tcp_server_socket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
tcp_server_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,True)
tcp_server_socket.bind(('192.168.124.131',8080))
tcp_server_socket.listen(128)
self.tcp_server_socket=tcp_server_socket
self.url_dict = {}
def start(self):
while True:
new_client_socket,ip_port=self.tcp_server_socket.accept()
self.handle(new_client_socket,ip_port)
def handle(self,new_client_socket,ip_port):
request_data=new_client_socket.recv(4096)
request_text=request_data.decode()
loc=request_text.find('\r\n')
request_line=request_text[:loc]
request_line_list=request_line.split(' ')
request_path=request_line_list[1]
self.judge(request_path,new_client_socket)
def judge(self,request_path,new_client_socket):
if request_path.endswith('.py'):
self.dict_funcs()
print(self.url_dict)
if request_path in self.url_dict:
func=self.url_dict[request_path]
response_body=func()
state='200 OK'
response_data=self.pinjie(response_body,state)
new_client_socket.send(response_data)
new_client_socket.close()
else:
response_body='您访问的页面不存在'.encode()
state='404 Not Found'
response_data=self.pinjie(response_body,state)
new_client_socket.send(response_data)
new_client_socket.close()
else:
if request_path=='/':
request_path='/index.html'
file_path='./static'+request_path
try:
with open(file_path,'rb')as file:
response_body=file.read()
state='200 OK'
response_data=self.pinjie(response_body,state)
new_client_socket.send(response_data)
new_client_socket.close()
except Exception as e:
print('找不到您请求的页面')
response_body='404 Not Found!'.encode()
state='404 Not Found'
response_data=self.pinjie(response_body,state)
new_client_socket.send(response_data)
new_client_socket.close()
return
def pinjie(self,response_body,state):
response_line='HTTP/1.1 %s\r\n'%state
response_headle='Server: Python20WS/2.1\r\n'
response_black='\r\n'
response_data=(response_line+response_headle+response_black).encode()+response_body
return response_data
def dict_funcs(self):
def func_dict(key):
def func_out(value):
self.url_dict[key]=value
def func_in():
return value()
return func_in
return func_out
@func_dict('/index.py')
def index():
with open('./templates/index.html','rb')as file:
response_body=file.read()
return response_body
@func_dict('/center.py')
def center():
with open('./templates/center.html', 'rb')as file:
response_body = file.read()
return response_body
@func_dict('/update.py')
def update():
with open('./templates/update.html', 'rb')as file:
response_body = file.read()
return response_body
if __name__ == '__main__':
ws=WebServer()
ws.start()