Web靜態伺服器 顯示需要的頁面

2021-08-11 14:27:16 字數 2272 閱讀 9562

#coding=utf-8

import socket

import re

from multiprocessing import process

#常量,所有字母全部大寫

#設定靜態檔案根目錄

html_root_dir="./html"

defhandle_client

(client_socket):

"""處理客戶端請求"""

# 獲取客戶端請求資料

request_data=client_socket.recv(1024)

print("request data:",request_data)

request_lines=request_data.splitlines()

for line in request_lines:

print(line)

#解析請求報文

#提取使用者請求的檔名

print(request_start_line.decode("utf-8"))

file_name=re.match(r"\w+ +(/[^ ]*) ",request_start_line.decode("utf-8")).group(1)

#常量寫在左邊,變數寫在右邊

if"/" == file_name:

file_name="/index.html"

#開啟檔案,讀取內容

try:

file=open(html_root_dir+file_name,"rb")

except ioerror:

# 構造響應資料

# 構造響應資料

#形成響應報文

response=response_start_line+response_headers+"\r\n"+response_body

print("response data:",response)

#注意編碼問題

#向客戶端返回響應資料

client_socket.send(bytes(response,"utf-8"))

#關閉客戶端socket連線

client_socket.close()

if __name__=="__main__":

#tcp socket 服務端

#af_inet---常量,某個具體數值

server_socket=socket.socket(socket.af_inet,socket.sock_stream)

server_socket.setsockopt(socket.sol_socket,socket.so_reuseaddr,1)

server_socket.bind(("",8000))

server_socket.listen(128)

while

true:

#返回乙個新的客戶端的套接字

client_socket, client_address = server_socket.accept()

# print("[%s,%s]使用者連線上了!"%(client_address[0],client_address[1]))

print("[%s,%s]使用者連線上了!" % client_address)

#新建程序

handle_client_process=process(target=handle_client,args=(client_socket,))

handle_client_process.start()

#client套接字關閉

client_socket.close()

Web靜態伺服器02 顯示需要的頁面

coding utf 8 import socket import re def handle client client socket 為乙個客戶端進行服務 如果沒有指定訪問哪個頁面。例如index.html 404表示沒有這個頁面 因為頭資訊在組織的時候,是按照字串組織的,不能與以二進位制開啟檔...

Web靜態伺服器 2 顯示需要的頁面

coding utf 8 import socket import re def handle client client socket 為乙個客戶端進行服務 如果沒有指定訪問哪個頁面。例如index.html 404表示沒有這個頁面 因為頭資訊在組織的時候,是按照字串組織的,不能與以二進位制開啟檔...

WEB靜態伺服器1 顯示固定頁面

import socket defhandle client client socket rec data client socket.recv 1024 decode gbk response line header rec data.splitlines for line in response...