1. 程式人生 > >python多程序的web伺服器的搭建

python多程序的web伺服器的搭建

web_server專案目錄:

  •  web_server
    • html(資料夾)
      • index.html
    • static_web_server.py

static_web_server.py編寫

import re
import socket

from multiprocessing import Process

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


def handle_client(client_socket):
    """處理客戶端請求"""

    # 接收客戶端請求資料(報文)
    request_data = client_socket.recv(1024)
    print("request_data:", request_data)

    # splitlines返回的是一個列表形式
    request_lines = request_data.splitlines()

    print("==" * 20)
    print(request_lines)
    print("==" * 20)
    for line in request_lines:
        print(line)

    # 'GET / HTTP/1.1'
    request_start_line = request_lines[0]
    print("*" * 20)
    # 使用者要請求的檔名(request_start_line由byte轉化成str型別)
    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_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 = "hello world"
        response_body = file_data.decode("utf-8")

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

    # 向客戶端返回響應資料
    # 字串轉化成位元組
    client_socket.send(bytes(response, "utf-8"))

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


if __name__ == '__main__':
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # 可以重複地址
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    # 接收任何IP地址,埠號8000
    server_socket.bind(("", 8000))
    # 監聽佇列大小設成128(最多連線128個使用者)
    server_socket.listen(128)

    # 採用多程序的使用者監聽
    while True:
        # 等待連線
        # 接收到的是客戶端的socket,和客戶端的地址
        client_socket, client_address = server_socket.accept()
        # 列印:第一個引數是:IP地址,第二個引數是:埠號(存在於client_address裡,它本身是個元組)
        # print("[%s,%s]使用者連線上" % (client_address[0], client_address[1]))
        print("[%s,%s]使用者連線上" % client_address)
        # Process引數target應該接收的是函式名,args接收的應該是個元組
        handle_client_process = Process(target=handle_client, args=(client_socket,))
        # 開啟程序
        handle_client_process.start()
        # 客戶端的socket已經沒有用了,關閉
        client_socket.close()

index.html的編寫 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My Web</title>
</head>
<body>
    <h1>Hello</h1>
    <p>welcome to my web</p>

</body>
</html>

 輸出:

[127.0.0.1,3657]使用者連線上
[127.0.0.1,3658]使用者連線上
request_data: b'GET /index.html HTTP/1.1\r\nHost: 127.0.0.1:8000\r\nConnection: keep-alive\r\nCache-Control: max-age=0\r\nUpgrade-Insecure-Requests: 1\r\nUser-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\r\nAccept-Encoding: gzip, deflate, br\r\nAccept-Language: zh-CN,zh;q=0.9\r\nCookie: Hm_lvt_dde6ba2851f3db0ddc415ce0f895822e=1529392663\r\n\r\n'
========================================
[b'GET /index.html HTTP/1.1', b'Host: 127.0.0.1:8000', b'Connection: keep-alive', b'Cache-Control: max-age=0', b'Upgrade-Insecure-Requests: 1', b'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36', b'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', b'Accept-Encoding: gzip, deflate, br', b'Accept-Language: zh-CN,zh;q=0.9', b'Cookie: Hm_lvt_dde6ba2851f3db0ddc415ce0f895822e=1529392663', b'']
========================================
b'GET /index.html HTTP/1.1'
b'Host: 127.0.0.1:8000'
b'Connection: keep-alive'
b'Cache-Control: max-age=0'
b'Upgrade-Insecure-Requests: 1'
b'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
b'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8'
b'Accept-Encoding: gzip, deflate, br'
b'Accept-Language: zh-CN,zh;q=0.9'
b'Cookie: Hm_lvt_dde6ba2851f3db0ddc415ce0f895822e=1529392663'
b''
********************
GET /index.html HTTP/1.1
####################
response data: HTTP/1.1 200 OK
Server:My server

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My Web</title>
</head>
<body>
    <h1>Hello</h1>
    <p>welcome to my web</p>

</body>
</html>
####################