Kliver Max
Kliver Max

Reputation: 5299

How to make multiple events with Flask SocketIO?

I have a socetio connection what provide search on button click:

$(document).ready(function () {
        var socket = io.connect('http://' + document.domain + ':' + location.port);
socket.on('connect', function () {
            socket.emit('seatch event', {
                data: 'App Started'
            })
            var form = $('form').on('submit', function (e) {
                let search_query = $('#search_text').val()
                socket.emit('search event', {
                    search_query: encodeURIComponent(search_query)
                })
            })
        });

socket.on('search_results_event', function (msg) {
    //do someting
});

Now i want to add another event, in my case i want to send data to server and recive answer each time when <li> element in list become activate.
How can i add this event? I have to add another connection?
Any advises?

Upvotes: 1

Views: 1059

Answers (1)

elembie
elembie

Reputation: 640

You don't need another connection. Once the socket is connected, you can just use socket.on as you already have to catch events emitted from the server, and emit e.g. socket.emit('[event_name], [data_object]) to send data to the server.

On the javacript side you emit like this

socket.emit('my_event', {'message': 'hello world'})

You can handle this on the flask side by

@socketio.on('my_event')
def handle_my_event(data):

    print('Received an instance of my_event')

    #  will print {'message': 'hello world'}
    print(data) 

Similarly you can emit events from the flask server, such as your search_results_event by

from flask_socketio import emit

emit('search_results_event', {'key': 'value'})

Which would be handled by your existing socket.on in the question. The second argument to emit is the data you want to send - usually json.

See the docs for more information.

Upvotes: 2

Related Questions