py文件
import socket
def server_run():
soc = socket.socket()
soc.bind(('127.0.0.1', 8008))
soc.listen(5)
while True:
conn, addr = soc.accept()
recv_data = conn.recv(1024)
print(recv_data)
# 1 直接在send里写,发送给客户端
# conn.send(b'HTTP/1.1 200 OK\r\n\r\n<h1>hello web</h1><img src="https://gss2.bdstatic.com/9fo3dSag_xI4khGkpoWK1HF6hhy/baike/c0%3Dbaike92%2C5%2C5%2C92%2C30/sign=5e3814acf9edab64607f4592965fc4a6/14ce36d3d539b600c0c465d0eb50352ac65cb74b.jpg"></img>')
#2 打开一个html文件,发送给客户端
# with open('index.html','r',encoding='utf-8') as f:
# data=f.read()
# conn.send(('HTTP/1.1 200 OK\r\n\r\n%s'%data).encode('utf-8'))
# 3 动态网页,字符串替换
import time
now=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print(now)
with open('index.html','r',encoding='utf-8') as f:
data=f.read()
data=data.replace('@@@',now)
conn.send(('HTTP/1.1 200 OK\r\n\r\n%s'%data).encode('utf-8'))
conn.close()
if __name__ == '__main__':
server_run()
index.html 文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h2>@@@</h2>
<img src="https://gss2.bdstatic.com/9fo3dSag_xI4khGkpoWK1HF6hhy/baike/c0%3Dbaike92%2C5%2C5%2C92%2C30/sign=5e3814acf9edab64607f4592965fc4a6/14ce36d3d539b600c0c465d0eb50352ac65cb74b.jpg" alt="">
</body>
</html>