PythonでB/Sサーバーをシミュレートする方法

Pythonを使用して基本的なB/Sサーバーを作成し、静的および動的なHTMLフィードバックを提供する方法について説明します。

接続の実現方法

ソケットは、アプリケーション層とトランスポート層の間に位置する仮想層であり、接続を管理するための一連のインターフェースを提供します。

B/Sクライアントとサーバー間の通信プロセス

クライアントがURLを指定してリクエストを送信すると、サーバー側でそのリクエストに基づいて適切な応答(HTMLページなど)を返します。

静的HTMLフィードバック用のSocketサーバーコード


import socket

server_socket = socket.socket()
server_socket.bind(("127.0.0.1", 8888))
server_socket.listen()

def get_index(url):
    with open("main_page.html", "r", encoding="utf-8") as file:
        content = file.read()
    return bytes(content, 'utf-8')

def get_about(url):
    with open("about_page.html", "r", encoding="utf-8") as file:
        content = file.read()
    return bytes(content, 'utf-8')

routes = {
    "/main/": get_index,
    "/about/": get_about
}

while True:
    client_conn, client_addr = server_socket.accept()
    request_data = client_conn.recv(8192).decode('utf-8')
    path = request_data.split()[1]
    client_conn.send(b'HTTP/1.1 200 OK\r\n\r\n')
    handler = routes.get(path)
    if handler:
        response = handler(path)
    else:
        response = b"404 Not Found"
    client_conn.send(response)
    client_conn.close()

indexページのHTMLコード


<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Main Page</title>
</head>
<body>
    <div>これはメインページです。</div>
</body>
</html>

aboutページのHTMLコード


<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>About Page</title>
</head>
<body>
    <div>これは「About」ページです。</div>
</body>
</html>

動的HTMLフィードバック用のSocketサーバーコード


import socket
from datetime import datetime

server_socket = socket.socket()
server_socket.bind(("127.0.0.1", 8888))
server_socket.listen()

def get_time(url):
    with open("time_page.html", "r", encoding="utf-8") as file:
        content = file.read().replace('@@timestamp@@', datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
    return bytes(content, 'utf-8')

routes = {
    "/main/": get_index,
    "/about/": get_about,
    "/current-time/": get_time
}

while True:
    client_conn, client_addr = server_socket.accept()
    request_data = client_conn.recv(8192).decode('utf-8')
    path = request_data.split()[1]
    client_conn.send(b'HTTP/1.1 200 OK\r\n\r\n')
    handler = routes.get(path)
    if handler:
        response = handler(path)
    else:
        response = b"404 Not Found"
    client_conn.send(response)
    client_conn.close()

タイムページのHTMLコード


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Current Time</title>
</head>
<body>
    <div>@@timestamp@@</div>
</body>
</html>

タグ: Python socket Browser-Server HTML

6月7日 18:37 投稿