salmans911
salmans911

Reputation: 1

Flask SocketIO duplicating saved messages

I am building a chat app based on Flask SocketIO only, no database. One of the requirements is when a new user connects, the app should show previous messages. I save every message into a array on each send event. Okay, so now the problem is, when User A connects and creates some messages, and then User B connects, all the previous messages from User B is shown, but then User A also gets that messages, so User A ends up duplicated messages.

Client Side JS

function myFunction() {
    document.getElementById('demo').style['text-decoration']='underline';
  }
  const socket = io.connect("http://127.0.0.1:5000");

socket.on('connect', function() {

  socket.emit('sync_messages');
  socket.emit('sync_channels');

});

Flask App Code

    @socketio.on('sync_messages')
def handle_sync():
    socketio.emit('show_all_messages', messages)

@socketio.on('sync_channels')
def handle_sync_channels():
    socketio.emit('show_all_channels', channels)

Visual representation of what is happening

what the actual bug is

Upvotes: 0

Views: 361

Answers (1)

Miguel Grinberg
Miguel Grinberg

Reputation: 67492

The socketio.emit() function is not context aware, it defaults to broadcasting to all connected users. Try using emit() which is the Flask-friendly wrapper:

@socketio.on('sync_messages')
def handle_sync():
    emit('show_all_messages', messages)

@socketio.on('sync_channels')
def handle_sync_channels():
    emit('show_all_channels', channels)

Upvotes: 0

Related Questions