(1)创建index.html和test.html,作为访问的资源;
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>indextitle>
head>
<body>
<h1>$@index@$h1>
body>
html>
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>testtitle>
head>
<body>
<h1>$@test@$h1>
body>
html>
(2)根据传入的参数,读取响应的HTML文件,并根据占位符进行替换实现网页动态显示。
import socket
def index(url):
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 fun404(url):
ret = "not found!
"
return bytes(ret, encoding='utf-8')
url_func = [ # 建立url与函数名的对应关系
('/index/', index),
('/test/', test)
]
# 建立socket服务,测试http://127.0.0.1:8000/index/
sk = socket.socket()
sk.bind(('127.0.0.1', 8000))
sk.listen()
print('socket服务开始运行...')
while True:
conn, addr = sk.accept()
data = conn.recv(1024)
#print(data) # 输出socket服务端接收的浏览器发送的消息
# 如果客户端没有发送新的数据就重新开始,不再向下执行,防止后面语句对空字符进行操作抛出异常
if not data:
continue
data_str = str(data, encoding='utf-8')
line = data_str.split('\r\n')
v1 = line[0].split()
url = v1[1]
conn.send(b"HTTP/1.1 200 OK\r\n\r\n")
func = None
for i in url_func: # 取出url_func中的每一项
if i[0] == url:
func = i[1]
break
if func:
func = func
else:
func = fun404
rep = func(url)
conn.send(rep) # 把函数返回值向客户端发送
conn.close()
(3)测试结果
在浏览器中分别输入http://127.0.0.1:8000/index/
和http://127.0.0.1:8000/test/
可以得到各自的影响结果。
(1)建立socket服务,绑定IP地址和端口号,启动监听进程并把本地计算机设置成socket服务端;
(2)服务启动后,通过循环语句,持续接收浏览器发送的信息;
(3)socket服务器与浏览器以字节形式在网络上传递信息,发送字符串之前必须要转换成字节形式;
(4)socket服务端与浏览器的消息传递必须要按照HTTP格式。