简体   繁体   English

使用 socket.IO 从 Flask 到 JS 的通知

[英]Notification from Flask to JS using socket.IO

I'm using the Flask-SocketIO library which works fine but I need to send a notification with emit to the outside of a socket.io decorator and it's a real pain.我正在使用工作正常的 Flask-SocketIO 库,但我需要向 socket.io 装饰器的外部发送带有发射的通知,这真的很痛苦。 Looking at the solutions, many people use rabbitmq or redis but I don't know how to use them.查看解决方案,很多人使用 rabbitmq 或 redis 但我不知道如何使用它们。

Here's my code:这是我的代码:

from flask import Flask, render_template
from flaskwebgui import FlaskUI
from flask_socketio import SocketIO, emit

app = Flask(__name__)
async_mode = None
app.config['SECRET_KEY'] = 'hello'
socketio = SocketIO(app, async_mode=async_mode, message_queue='amqp:///socketio')

def run_sock(): 
    socketio.run(app, debug=True)

ui = FlaskUI(app, fullscreen=True, server=run_sock,)

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

@socketio.on('test', namespace='/test')
def test():
    print("test")

if __name__ == "__main__":
    ui.run()
    io = SocketIO(message_queue='amqp:///socketio')
    io.emit('test_emit', {'data': 'toto'}, namespace='/test')

My JS front-end never gets the test_emit message, how do I do?我的 JS 前端从来没有收到 test_emit 消息,我该怎么办?

The problem with your emit is that it appears below the ui.run() call, which does not return until you close the application.您的 emit 问题在于它出现在ui.run()调用下方,直到您关闭应用程序才会返回。 Move the emit to any function in your application that executes while the server is running (such as a Flask view function) and it should work just fine.将发射移动到服务器运行时执行的应用程序中的任何 function(例如 Flask 视图函数),它应该可以正常工作。

Why do you have two SocketIO objects in the same process?为什么在同一个进程中有两个SocketIO对象? The socketio instance that you defined near the top of the script can be used anywhere within the process, no need to create a second instance.您在脚本顶部附近定义的socketio实例可以在进程中的任何地方使用,无需创建第二个实例。 You do not need to use a message queue for this problem, since you have all the usages of Socket.IO within a single process.对于这个问题,您不需要使用消息队列,因为您在单个进程中拥有 Socket.IO 的所有用法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM