How to send messages to all clients with Flask-SocketIO?

3.6k views Asked by At

I'm trying to learn Flask-SocketIO, Now i'm trying to do simple chat, but no one receives messages except the user in browser. Python/Flask code:

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

app = Flask(__name__)
app.config['SECRET_KEY'] = '?-.'
socketio = SocketIO(app)

@socketio.on('joined')
def handle_message(who):
    emit('back', who)

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

if __name__ == '__main__':
    socketio.run(app)

and Javascript:

var socket = io.connect('http://' + document.domain + ':' + location.port);
    $('#mybut').on("click", function(){
      socket.emit('joined', {who:'someone'});
  });
    socket.on('back', function(data) {
      console.log(data['who'] + ' joined.')
  });
1

There are 1 answers

0
svens On BEST ANSWER

You need to set the broadcast parameter in this case. Check the Flask-SocketIO docs on broadcasting.

I.e. change your handler to the following:

@socketio.on('joined')
def handle_message(who):
    emit('back', who, broadcast=True)