flask socketio emit to specific user
<p>I see there is a question about this topic, but the specific code is not outlined. Say I want to emit only to the first client.</p>

<p>For example (in events.py):</p>

<pre><code>clients = []

@socketio.on('joined', namespace='/chat')
def joined(message):
    """Sent by clients when they enter a room.
    A status message is broadcast to all people in the room."""
    #Add client to client list
    clients.append([session.get('name'), request.namespace])
    room = session.get('room')
    join_room(room)
    emit('status', {'msg': session.get('name') + ' has entered the room.'}, room=room)
    #I want to do something like this, emit message to the first client
    clients[0].emit('status', {'msg': session.get('name') + ' has entered the room.'}, room=room)
</code></pre>

<p>How is this done properly?</p>

<p>Thanks</p>

<p>I'm not sure I understand the logic behind emitting to the first client, but anyway, this is how to do it:</p>

<pre><code>clients = []

@socketio.on('joined', namespace='/chat')
def joined(message):
    """Sent by clients when they enter a room.
    A status message is broadcast to all people in the room."""
    # Add client to client list
    clients.append(request.sid)

    room = session.get('room')
    join_room(room)

    # emit to the first client that joined the room
    emit('status', {'msg': session.get('name') + ' has entered the room.'}, room=clients[0])
</code></pre>

<p>As you can see, each client has a room for itself. The name of that room is the Socket.IO session id, which you can get as <code>request.sid</code> when you are handling an event from that client. So all you need to do is store this <code>sid</code> value for all your clients, and then use the desired one as room name in the <code>emit</code> call.</p>

python flask flask-socketio