Qbik
Qbik

Reputation: 6147

Flask socketIO emit series of events

I would like server to emit series of events to client (React) after connection is established, Ive tried:

@socketio.on('connect')
def test_connect():
    for i in range(10):
        emit('my response', {'data': 'Connected ' + str(i)})
        time_module.sleep(2)

but events shows in web browser console at the same time, like they arrived at the same moment, in react I use :

useEffect(() => {
    const socket = socketIOClient(ENDPOINT);

    socket.on('my response', function (data) {
      console.log('my response: ', data.data);
    })
})

Upvotes: 0

Views: 132

Answers (1)

Miguel Grinberg
Miguel Grinberg

Reputation: 67509

There are two potential problems in your server code.

First of all, what is time_module in your example? I suspect that is a blocking sleep that you are doing. Instead, I suggest you sleep properly with socketio.sleep(2).

The second problem is that you are doing this in the connect event handler. The Socket.IO server waits until you return from the connect handler to decide if the client is accepted or rejected, so in general you do not want this handler to take a long time to run, because the connection isn't fully established until you return. I suggest you move this logic to a background function instead.

The following code addresses both issues:

def initial_events():
    for i in range(10):
        emit('my response', {'data': 'Connected ' + str(i)})
        socketio.sleep(2)

@socketio.on('connect')
def test_connect():
    socketio.start_background_task(initial_events)

Upvotes: 1

Related Questions