【问题标题】:flask socketio emit to specific user烧瓶 socketio 向特定用户发出
【发布时间】:2017-01-18 07:36:42
【问题描述】:

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

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

这是如何正确完成的?

谢谢

【问题讨论】:

    标签: python flask flask-socketio


    【解决方案1】:

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

    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 调用中使用所需的值作为房间名称。

    【讨论】:

    • 您好,感谢您的快速回复!是的,我实际上不会这样做,我只是想创建一个示例,您将在其中向特定客户端发出。再次感谢 Miguel,非常感谢!
    • 如果我使用数据库,我可以创建一个新列,f.e. user_room 并在那里保存一个唯一的字符串,可以识别该用户进行私人聊天?
    • 我在另一条评论中问过这个问题,但使用唯一用户 ID 是愚蠢的,因为有人很容易猜到它并加入私人对话,对吧?
    • @Miguel 为所有客户创建一个单独的房间是向特定客户发射的唯一方法吗?我有一项很长的任务需要在服务器/后端完成。我没有使用轮询,而是使用 celery flask 应用程序,一旦工作完成,我希望将结果发送给发起请求的特定人。
    • 每个客户端在连接时会自动分配一个房间。使用sid 作为房间的名称。
    猜你喜欢
    • 2015-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-22
    • 2017-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多