Flask Socketio不更新数据

问题描述

我正在与Flask Socketio合作。现在,我的代码控制台在用户每次打开页面时记录日志。但是,当我在新标签页/窗口中打开页面时,原始用户的控制台未更新。下面是代码,看看吧

  let socket = io.connect("http://127.0.0.1:5000/")
socket.on("connect",() => {
    socket.emit("my custom event",{text:"I have joined"})
  })
  socket.on("my response",function(msg) {
    console.log(msg)
  })

这是flask的python代码

from flask import Flask,render_template,request
import requests
from flask_socketio import SocketIO,emit,send

app = Flask(__name__)

app.config["SECRET_KEY"] = "hope"
socketio = SocketIO(app)


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


@app.route('/1')
def random_route():
    return render_template("index2.html")


@socketio.on('message')
def message(data):
    print(data)


@socketio.on('my custom event')
def handle_custom_event(data):
    emit("my response",data)


if __name__ == "__main__":
    socketio.run(app,debug=True)

解决方法

emit函数的默认设置是仅将事件发送给发件人。如果要寻址所有已连接的客户端,则必须使用broadcast选项进行指示:

@socketio.on('my custom event')
def handle_custom_event(data):
    emit("my response",data,broadcast=True)