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
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.