Webサーバに繋っているブラウザが、全部いなくなったことを確認するプログラム

2024年2月8日

Webサーバに繋っているブラウザが、全部いなくなったことを確認する為に、ブラウザのJavaScriptからハートビートを飛ばして、ハートビートがこなくなったことを確認する簡易プログラムを作成しました。

■ブラウザの生存監視サーバ

$ pip install Flask

をしてから、以下のプログラムをhearbeat.pyという名前でサーバを立ち上げるフォルダ(例 c:\users\ebata)に放り込んでおく。

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/heartbeat', methods=['POST'])
def receive_heartbeat():
    data = request.get_json()
    print(f"Received heartbeat: {data}")
    return jsonify({"status": "OK"})

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=3000)

■index.htmlの内容
これも、サーバを立ち上げるフォルダ(例 c:\users\ebata)に放り込んでおく。

<!DOCTYPE html>
<html>
<head>
    <title>Heartbeat Example</title>
</head>
<body>
    <h1>Heartbeat Sender</h1>
    <script>
        function sendHeartbeat() {
            fetch('http://localhost:3000/heartbeat', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ timestamp: new Date() })
            })
            .then(response => response.json())
            .then(data => console.log('Heartbeat sent:', data))
            .catch(error => console.error('Error sending heartbeat:', error));
        }

        // 10秒ごとにハートビートを送信
        setInterval(sendHeartbeat, 10000);
    </script>
</body>
</html>

■起動方法
(Step 1)サーバを立ち上げるフォルダ(例 c:\users\ebata)で、

C:\Users\ebata>python heartbeat.py

で、「ブラウザの生存監視するサーバ」を起動
(Step 2)次に、以下のコマンドで、1行Webサーバを起動

C:\Users\ebata>python -m http.server 8000

(Step 3) ブラウザに、

http://localhost:8000/

を投入。複数のブラウザを立ち上げて、ブラウザの生存監視サーバから、

の表示が出てくれば成功 → ウソです。
ブラウザを全部落せば、動かなくなるはずです。→ これは本当ですが、def receive_heartbeat()の処理は全くされていません


Choromeの開発者の表示は、こんなのが出ていました。

Access to fetch at 'http://localhost:3000/heartbeat' from origin 'http://localhost:8000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. (index):19 Error sending heartbeat: TypeError: Failed to fetch at sendHeartbeat ((index):10:13)

で、
このエラーメッセージは、CORS(Cross-Origin Resource Sharing)ポリシーに違反していることを示していて、これは、異なるオリジン(localhost:8000とlocalhost:3000)間でのリクエストがブラウザによってブロックされていることを意味します。

この問題を解決するために、FlaskアプリケーションでCORSポリシーを設定する必要があり、Flask-CORSという拡張機能を使用してこれを行うことができます。

pip install flask-cors

で、

from flask import Flask, request, jsonify
from flask_cors import CORS

app = Flask(__name__)
CORS(app) # すべてのリクエストに対してCORSを有効にする

を処理すれば、receive_heartbeat():が実施されます。

で、修正後のコードは以下の通りです。

from flask import Flask, request, jsonify
from flask_cors import CORS

app = Flask(__name__)
CORS(app)  # すべてのリクエストに対してCORSを有効にする

@app.route('/heartbeat', methods=['POST'])
def receive_heartbeat():
    data = request.get_json()
    print(f"Received heartbeat: {data}")
    return jsonify({"status": "OK"})

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=3000)

出力結果

ちょっとまだ疑問はあるけど、とりあえず、メソッドの中には入ったようです。

 

 

2024年2月8日2023,江端さんの技術メモ

Posted by ebata