# -*- encoding:utf-8 -*-
#引入socket模块
import socket
#创建socket服务
sk= socket.socket()
#绑定IP及端口
sk.bind(('localhost',8000))
#监听
sk.listen()
print("socket 开始运行")
def index(url):
#读取html文件,并对占位符进行替换
#with用法:在退出with代码块后自动关闭with打开的文件
with open('index.html','r',encoding='utf-8') as f:
rd=f.read()
rd = rd.replace('$@index$@','首页')
return bytes(rd,encoding='utf-8')
def test(url):
with open('test.html','r',encoding='utf-8') as f:
rd=f.read()
rd=rd.replace('$@test$@','测试')
return bytes(rd,encoding='utf-8')
def nofound404(url):
ret='<h1>page no found!</h1>'
return bytes(ret,encoding='utf-8')
# [("/index/",index),("/test/",test)]
url_func={"/index/" : index,"/test/" : test}
while True:
print('While...')
#接收socket客户端请求
conn,addr=sk.accept()
#data变量接收客户端数据
data=conn.recv(1024)
print(data)
#服务端接收到数据请求后就要做出响应及有request就要response
#现在response
# 如果客户端没有发送新的数据,就重新开始,不再向下执行
# 防止后面的语句对空字符进行操作而抛出异常
# continue
# 把接收到的字节形式的数据转换成字符串,一般用到的编码方式:utf-8
data_str = str(data)
# 以\r\n分割每一行
line = data_str.split('\r\n')
print(line)
# 取出第一行字符串line[0]后再用split()继续分割
v1 = line[0].split()
print('v1-----------------', v1)
url = v1[1]
print('url',url)
# 响应客户端的请求,字符串前加b表示以字节形式传递
conn.send(b"HTTP/1.1 200 OK\r\n\r\n")
func = None #存取函数名用
print(type(func))
# 用for循环取出url_func中的每一项,它是由url和函数名组成的元组向客户端发消息
for k,v in url_func.items():
print('---k---',k,url)
if k == url:
func = v
print(type(func))
break
else:
func = nofound404
rep = func(url)#字典的v的值就是函数名
print(rep)
conn.send(rep)
![]()