Flask SocketIO:向特定用户发出emit

27

我看到有一个关于这个主题的问题,但具体的代码没有概述。比如说我只想向第一个客户端发出信号。

例如(在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)

如何正确地完成这个任务?

谢谢

1个回答

33

我不确定我理解在向第一个客户端发出信号的逻辑背后的原因,但是无论如何,以下是如何实现:

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,您可以在处理来自该客户端的事件时获取该ID,方法是使用request.sid。因此,您只需要为所有客户端存储此sid值,然后在emit调用中使用所需的值作为房间名称即可。


如果我使用数据库,我可以创建一个新的列,例如user_room,并在其中保存一个唯一的字符串,用于识别该用户进行私人聊天? - Roman
在这个示例中,clients[0]session.get('room')是相同的吗?我们不应该执行join_room(request.sid)吗? - Phani Rithvij
2
@Miguel,为所有客户端创建单独的房间是向特定客户端发出信号的唯一方法吗?我有一个需要在服务器/后端完成的长时间任务。我使用了Celery Flask应用程序,而不是轮询,一旦作业完成,我希望将结果发送给发起请求的特定用户。 - Naman
1
每个客户端在连接时都会自动分配一个房间。使用 sid 作为房间的名称。 - Miguel Grinberg
Flask-SocketIO并没有提供任何可以帮助解决这个问题的功能,但是您的应用程序可以将任何连接的客户端视为特殊情况,并与其他客户端进行不同的处理。 - Miguel Grinberg
显示剩余6条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接