1. 程式人生 > >python網路-靜態Web伺服器案例(29)

python網路-靜態Web伺服器案例(29)

一、靜態Web伺服器案例程式碼static_web_server.py

# coding:utf-8

# 匯入socket模組
import socket
# 匯入正則表示式模組
import re
# 匯入多程序模組
from multiprocessing import Process

# 設定靜態檔案根目錄
HTML_ROOT_DIR = "./html"


# 定義個一個HTTPServer的類
class HTTPServer(object):
    """"""

    # 初始化方法
    def __init__(self):
        # 建立一個伺服器socket套接字
        self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # socket地址重用配置
        self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    # HTTPServer開啟的方法
    def start(self):
        # 設定監聽位元組長度為128
        self.server_socket.listen(128)
        # 不間斷的監聽是否有人鏈接伺服器
        while True:
            # 解析請求連結伺服器的客戶端資訊
            client_socket, client_address = self.server_socket.accept()
            print("[%s:%s]使用者連線上了" % client_address)
            # 建立多程序handle_client處理客戶端的請求
            handle_client_process = Process(target=self.handle_client, args=(client_socket,))
            # 開啟多程序
            handle_client_process.start()
            # 關閉客戶端socket套接字
            client_socket.close()

    # 多程序handle_client
    def handle_client(self, client_socket):
        """處理客戶端請求"""
        # 獲取客戶端資料
        request_data = client_socket.recv(1024)

        print("request data:", request_data)
        # 多請求資料用空格做分割處理
        request_headers_lines = request_data.splitlines()
        for line in request_headers_lines:
            print(line)

        # 解析請求報文
        request_start_line = request_headers_lines[0]

        # 利用正則表示式提取使用者請求的檔名
        file_name = re.match(r"\w+ +(/[^ ]*) ", request_start_line.decode("utf-8")).group(1)
        print(file_name)
        if "/" == file_name:
            file_name = "/index.html"

        # 開啟檔案 ,讀取內容
        try:
            file = open(HTML_ROOT_DIR + file_name, "rb")
        except IOError:
            # 設定開啟檔案失敗時返回的響應起始行\r\n是換行
            response_start_line = "HTTP/1.1 404 Not Found\r\n"
            # 設定開啟檔案失敗時返回的響應頭
            response_headers = "Server:My server\r\n"
            # 設定開啟檔案失敗時返回的響應體
            response_body = "The File is not found"
        else:
            # 開啟成功時讀取的客戶端要請求的檔案資料
            file_data = file.read()
            # 關閉檔案
            file.close()

            # 構造響應資料
            response_start_line = "HTTP/1.1 200 OK\r\n"
            # 構造響應頭
            response_headers = "Server:My server\r\n"
            # 構造響應體
            response_body = file_data.decode("utf-8")

        response = response_start_line + response_headers + "\r\n" + response_body
        print("response data:", response)

        # 向客戶端返回響應資料
        client_socket.send(bytes(response, "utf-8"))

        # 關閉客戶端連線
        client_socket.close()

    # 繫結埠
    def bind(self, port):
        self.server_socket.bind(("", port))


def main():
    # 建立HTTPServer物件
    http_server = HTTPServer()
    # 繫結埠
    http_server.bind(8000)
    # 開啟服務
    http_server.start()


if __name__ == "__main__":
    main()

二、index.html程式碼

說明:index.html在html資料夾中,html資料夾和static_web_server.py在同目錄

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My web</title>
</head>
<body>
    <h1>Se7eN_HOU</h1>
</body>
</html>

三、瀏覽器執行效果 

四、說明

在Web應用中,伺服器把網頁傳給瀏覽器,實際上就是把網頁的HTML程式碼傳送給瀏覽器,讓瀏覽器顯示出來。而瀏覽器和伺服器之間的傳輸協議是HTTP,所以:

  • HTML是一種用來定義網頁的文字,會HTML,就可以編寫網頁;

  • HTTP是在網路上傳輸HTML的協議,用於瀏覽器和伺服器的通訊

&n