import socket
def f1(request):
"""
处理用户请求,并返回相应的内容
:param request: 用户请求的所有信息
:return:
"""
f = open('index.fsw','rb')
data = f.read()
f.close()
return data
"""
<body>
<h1>用户登录</h1>
<form>
<p><input type="text" placeholder="用户名" /></p>
<p><input type="password" placeholder="密码" /></p>
</form>
</body>
"""
def f2(request):
f = open('aricle.tpl','rb')
data = f.read()
f.close()
print(data)
return data
"""
<body>
<table border="1">
<thead>
<tr>
<th>ID</th>
<th>用户名</th>
<th>邮箱</th>
</tr>
</thead>
<tbody>
<tr>
<th>1</th>
<th>root</th>
<th>root@qq.com</th>
</tr>
</tbody>
</table>
</body>
"""
routers = [
('/xxx', f1),
('/ooo', f2),
]#手动写的网址
def run():
sock = socket.socket()
sock.bind(('127.0.0.1',8080))
sock.listen(5)
while True:
conn,addr = sock.accept() # hang住
#print(conn)#获得的两个套接字,我去charm自己会发送请求一个/favicon.ico页面的报文
# print(addr)
# 有人来连接了
# 获取用户发送的数据
data = conn.recv(8096)
data = str(data,encoding='utf-8')
#print(data)#get报文
headers,bodys = data.split('\r\n\r\n')
#print("head:",headers)
#print("body:",bodys) body是空的
temp_list = headers.split('\r\n')
# print(temp_list)
method,url,protocal = temp_list[0].split(' ')
# print(method) GET
# print(url) /ooo /favicon.ico
# print(protocal) /HTTP/1.1
conn.send(b"HTTP/1.1 200 OK\r\n\r\n")
func_name = None
for item in routers:
if item[0] == url:
func_name = item[1]
break
if func_name:
response = func_name(data)
print(data)
else:
response = b"404"
conn.send(response)
conn.close()
if __name__ == '__main__':
run()