烧瓶socketio向特定用户发出

she*_*ell 6 python flask flask-socketio

我看到有关于此主题的问题,但具体代码未概述.假设我只想向第一个客户端发射.

例如(在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)
Run Code Online (Sandbox Code Playgroud)

这怎么做得好?

谢谢

Mig*_*uel 9

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

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])
Run Code Online (Sandbox Code Playgroud)

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

  • @Miguel 为所有客户端创建一个单独的房间是向特定客户端发送的唯一方法吗?我有一项很长的任务需要在服务器/后端完成。我没有使用轮询,而是使用了芹菜烧瓶应用程序,一旦工作完成,我希望将结果发送给发起请求的特定人。 (2认同)