向所有连接的客户端广播,除了使用python flask socketio的发件人

Tom*_*ins 7 python flask socket.io

我正在关注Alex Hadik的Flask Socketio教程,该教程构建了一个非常简单的烧瓶聊天应用程序.

http://www.alexhadik.com/blog/2015/1/29/using-socketio-with-python-and-flask-on-heroku

我想向除发件人之外的所有连接用户广播一条消息.我已经通过了flasksocketio init .py,但我仍然不确定如何做到这一点.

这是服务器代码.

from flask import Flask, render_template,request
from flask.ext.socketio import SocketIO,emit,send
import json,sys

app = Flask(__name__)
socketio = SocketIO(app)
clients = {}
@app.route("/")
def index():
    return render_template('index.html',)

@socketio.on('send_message')
def handle_source(json_data):
    text = json_data['message'].encode('ascii', 'ignore')
    current_client = request.namespace
    current_client_id = request.namespace.socket.sessid
    update_client_list(current_client,current_client_id)
    if clients.keys():
        for client in clients.keys():
            if not current_client_id in client:
                clients[client].socketio.emit('echo', {'echo': 'Server Says: '+text})       

def update_client_list(current_client,current_client_id):
    if not current_client_id in clients: clients[current_client_id] = current_client
    return 

if __name__ == "__main__":
    socketio.run(app,debug = False)
Run Code Online (Sandbox Code Playgroud)

它目前只是向所有连接的客户端广播.我创建了一个连接客户端dict(客户端),它存储由客户端ID索引的request.namespace.为发送客户端以外的所有客户端调用客户端[client] .socketio.emit()仍然会将消息广播给呼叫用户.

有没有人对如何向除发件人之外的所有连接用户广播消息有任何想法?

Gab*_*ssu 11

您不必保存用户 ID 和管理个人排放,您可以指定一个没有发送者的广播emit('my_event', {data:my_data}, broadcast=True, include_self=False)。在你的情况下,它会是这样的:

@socketio.on('send_message')
    def handle_source(json_data):
        text = json_data['message'].encode('ascii', 'ignore')
        emit('echo', {'echo': 'Server Says: '+text}, broadcast=True, include_self=False)
Run Code Online (Sandbox Code Playgroud)

如果您必须为特定的客户群发送消息,您可以创建房间,然后emit('my_event', {data:my_data}, room=my_room, include_self=False)用于向加入的客户发送消息my_room。您可以查看flask_socketio.emit的参考以了解更多详细信息。


Ale*_*dik 0

您可以尝试socket.broadcast.emit代替socket.emit. 我不确定这是否适用于 Python 库,但它是您在 Socket.io for Node.js 中寻找的语法。