flask socketio 发送给特定用户

flask socketio emit to specific user

我看到有关于这个话题的问题,但是没有列出具体的代码。假设我只想发送给第一个客户。

例如(在events.py):

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)

这是如何正确完成的?

谢谢

我不确定我是否理解发送给第一个客户端的逻辑,但无论如何,这是如何做到的:

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])

如您所见,每个客户都有自己的房间。该房间的名称是 Socket.IO 会话 ID,当您处理来自该客户端的事件时,您可以获得 request.sid。因此,您需要做的就是为所有客户存储此 sid 值,然后在 emit 调用中使用所需的值作为房间名称。