Search code examples
pythonflaskwebsocketsocket.ioflask-socketio

Private chat with flask-socketio


I'm developing a webapp for a personal assistant. While a user is connected to the site, I want them to be able to subscribe to their personal notifications while they're online. I went about doing this with socketio and flask socketio and I thought that I could just use multithreading, like so:

def update_loop():
    while my_update_condition:
        if my_update_exists:
            socketio.emit("update", my_update)

@socketio.on("get_updates")
def get_updates(data):
    '''Websocket thread for getting updates'''
    socketio.emit("debug", {"value": "Starting update loop"})
    update_thread = threading.Thread(target=update_loop)
    update_thread.start()

But my code using this strategy gives any update to all users online. Using flask socketio, how can I securely implement a private chat? The data in the updates isn't ultra-sensitive, but, since it's notifications that the user sets, it's usually personal. Thanks. Note: In my research on this I came upon something using a socketid to send a message just to a specific sender, but I couldn't find an example implementation of this using flask-socketio.


Solution

  • The socketio.emit() function broadcasts to all users by default. To address a message to a single user, you have to set the room to the desired user's room, which is named after the session id of the user. Here is an example:

    def update_loop(sid):
        while my_update_condition:
            if my_update_exists:
                socketio.emit("update", my_update, room=sid)
    
    @socketio.on("get_updates")
    def get_updates(data):
        '''Websocket thread for getting updates'''
        socketio.emit("debug", {"value": "Starting update loop"})
        update_thread = threading.Thread(target=update_loop, args=(request.sid,))
        update_thread.start()