简体   繁体   中英

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. Looking at the solutions, many people use rabbitmq or redis but I don't know how to use them.

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?

The problem with your emit is that it appears below the ui.run() call, which does not return until you close the application. 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.

Why do you have two SocketIO objects in the same process? 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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