python - 发生某些事件时,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)
我的意图是,每个客户端都不会从服务器接收此消息,而是转到不同的页面。
解决方案
我已经查看了代码。'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>
推荐阅读
- c# - EF Core,一对多关系,多个表和单个外部表
- javascript - 为什么我的下拉列表从谷歌表更新 webapp 中的第二个依赖下拉列表这么慢
- javascript - 为什么我的 .js 文件没有在我的网站上运行?
- google-sheets - 您可以在嵌入 Google 表格时从底部删除底部部分(导航箭头和表格名称)吗?
- openstreetmap - 是否可以在 OSRM 查询中定义高度限制?
- python - 使用 TKinter 输入框搜索并调出框架
- python - linux和windows版本的SQLite有区别吗
- anchor - 多于一个活动菜单处于活动状态
- json - 如何将 JSON 文件上传到 BigQuery
- python-3.x - 一次解析多个 XML/HTML 页面时出错