小程序
tcp服務(wù)端響應(yīng)客戶端發(fā)送的靜態(tài)資源請求 面向函數(shù)編程
import re
import socket
def init_server():
"""初始化tcp服務(wù)器"""
#1.創(chuàng)建socket
#2.綁定
#3.被動
#1.創(chuàng)建套接字對象
tcp_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#2.綁定端口
tcp_server.bind(("",7890))
#3.改成被動模式
tcp_server.listen(128)
#返回初始化的結(jié)果
return tcp_server
def client_exec(client):
"""處理用戶的請求,根據(jù)不同的地址返回不同的網(wǎng)頁"""
#得到地址
request_heads = client.recv(1024).decode()
#GET /index.html HTTP/1.1
head_lines = request_heads.splitlines()
first_head = head_lines[0]
file_name = re.match(r'[^/]+(/[^ ]*)', first_head).group(1)
#判斷/
if file_name == "/":
file_name = "/index.html"
try:
#打開相應(yīng)的文件
with open("./html%s"%file_name,"rb") as f:
content_page = f.read()
#發(fā)送
#響應(yīng)格式:
# 響應(yīng)頭
# 空行
# 響應(yīng)體
head = "HTTP/1.1 200 OK \r\n"
content = head + "\r\n"
client.send(content.encode("utf-8"))
client.send(content_page)
except Exception as e:
print(e)
head = "HTTP/1.1 404 NOT FOUND \r\n"
body = "not page is find!"
content = head + "\r\n" + body
client.send(content.encode("utf-8"))
def run_server(server):
"""開啟服務(wù)處理用戶請求"""
while True:
client,address = server.accept()
#處理用戶請求
client_exec(client)
def main():
"""處理瀏覽器請求"""
#1.創(chuàng)建tcp服務(wù)器
#2.開啟服務(wù)去循環(huán)接收用戶的請求并處理
#3.關(guān)閉
#一個函數(shù)一個功能
#1.初始化tcp服務(wù)器
server = init_server()
#2.開啟服務(wù)處理用戶請求
run_server(server)
#3.關(guān)閉
server.close()
if __name__ == '__main__':
main()