Registering server events with flask SocketIO

2019-02-25 17:42发布

问题:

I'm getting started with flask and SocketIO using https://github.com/miguelgrinberg/Flask-SocketIO.

I want to post a string to the flask server and then via SocketIO, emit this to the client webpage.

Normally my posting code would look like:

@app.route('/index',methods=['POST'])
def index():
    token = request.form['token']

As far as I understand, something like the following is needed to emit data from the server to client page:

@socketio.on('event', namespace='/test')
def test_message(message):
    emit('my response', {'data': message['data']}, broadcast=False)

It's not clear to me how to tie the 2 functions together so that on a post the value of token would be emitted to the client.

The closest I can find in the docs is:

Receiving Messages¶
When using SocketIO messages are received by both parties as events. On the client side Javascript callbacks are used. With Flask-SocketIO the server needs to register handlers for these events, similarly to how routes are handled by view functions.

How can I get this working?

回答1:

You're right with your assumptions. First, POST the data to Flask:

.ajax({
    url: "{{ url_for('index') }}",
    method: "POST",
    data: {
        token: "value"
    }
});

Your view would look like

@app.route('/index',methods=['POST'])
def index():
    token = request.form['token']
    test_message(dict(data=token))
    return '1'

And your JavaScript would look something like

var socket = io.connect('http://' + document.domain + ':' + location.port + namespace);
socket.on('connect', function() {
    socket.emit('my event', {data: 'I\'m connected!'});
});
socket.on('my response', function(msg) {
    // do something with msg.data
});