烧瓶插座向特定用户发出 [英] flask socketio emit to specific user

查看:86
本文介绍了烧瓶插座向特定用户发出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到有关此主题的问题,但未概述特定代码.假设我只想向第一个客户发出信号.

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.

例如(在events.py中):

For example (in 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)

这如何正确完成?

谢谢

推荐答案

我不确定我是否了解向第一个客户端发出消息的逻辑,但是无论如何,这是这样做的:

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

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

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 request.sid when you are handling an event from that client. So all you need to do is store this sid value for all your clients, and then use the desired one as room name in the emit call.

这篇关于烧瓶插座向特定用户发出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆