0

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

1 Answers1

0

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)
Miguel Grinberg
  • 65,299
  • 14
  • 133
  • 152
  • Woah, its the creator himself!!! Forgive me for this, but what exactly is the difference between emit and socketio.emit – salmans911 May 09 '20 at 18:14
  • The `socketio.emit()` function is fairly generic and not Flask specific. You could consider this function as an internal function that actually does the work. The `emit()` function is the public function of this extension. It is Flask specific, uses the request context to add sensible defaults to your emit, and of course calls into `socketio.emit()` to carry out the work. Things such as the namespace and the recipient of an emit get defaults based on the sender when you use `emit()`. Hope this helps! – Miguel Grinberg May 10 '20 at 14:08