首页 > 解决方案 > 发生某些事件时,Flask 服务器将所有连接的客户端重定向到页面

问题描述

我对 Flask、JavaScript、HTML 等非常陌生。所以,这可能是一个愚蠢的问题。

我有一个连接了一个客户端的 Flask 服务器。当这个客户端按下一个按钮时,服务器会向它发送一个新页面。这很容易,我知道该怎么做。

现在,假设有多个客户端连接到服务器。当其中一个客户按下该按钮时,是否有可能以及如何将新页面发送给所有客户?我已经尝试过使用 socketIO,我可以让服务器捕获按钮单击,并向所有客户端发送一条短信,但这会终止我的成功。我无法在所有客户端进行页面更改。

当客户端连接到 127.0.0.1:5000 时,服务器会渲染 index.html

@app.route('/')
def index():
    return render_template('index.html')

这是 index.html

<body>
    <input type="text" id="message">


    <button id="send">Send</button>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/3.1.3/socket.io.min.js"></script>
    <script
              src="https://code.jquery.com/jquery-3.6.0.js"
              integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk="
              crossorigin="anonymous"></script>

    <script src="{{ url_for('static', filename='script.js')}}"></script>
</body>

这是js文件

$(document).ready(function() {

    var socket = io.connect('http://127.0.0.1:5000');

    $('#send').on('click', function() {
        var message = $('#message').val();

        socket.emit('message from user', message);
    });

    socket.on('from Flask', function(msg) {
        alert(msg);
    });
...

当用户点击按钮时,服务器将客户端发送的消息向上广播并广播给所有连接的客户端。然后每个客户端在弹出窗口中显示它。

@socketio.on('message from user')
def receive_message_from_user(message):
    print ('USER MESSAGE {}'.format(message))
    emit ('from Flask', message.upper(), broadcast=True)

我的意图是,每个客户端都不会从服务器接收此消息,而是转到不同的页面。

标签: pythonflaskwebsocketsocket.io

解决方案


我已经查看了代码。'from Flask' 广播确实有效。

@socketio.on('message from user')
def receive_message_from_user(message):
    print ('USER MESSAGE {}'.format(message))
    emit('from Flask', message.upper(), broadcast=True)
    emit('redirect', {'url': url_for('home')}, broadcast=True)

(js)

socket.on('from Flask', function(msg) {
        alert("from flask: " + msg);
    });

可能让您感到困惑的是,它仅在您不在索引页面中时才有效,这是因为 home 没有导入 script.js。这将使消息出现(尽管您可能希望有两个不同的脚本,否则重定向也会在主页上被激活)。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Home</title>
</head>
<body>
    <h1>Home!!</h1>
 <script src="{{ url_for('static', filename='script.js')}}"></script>
</body>
</html>

推荐阅读