【发布时间】:2015-05-29 18:27:17
【问题描述】:
我正在关注 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)
目前只是向所有连接的客户端广播。我创建了一个连接的客户端字典(客户端),它存储由客户端 ID 索引的 request.namespace。 为除发送客户端之外的所有客户端调用 clients[client].socketio.emit() 仍会导致消息被广播给调用用户。
有人对我如何向除发件人以外的所有连接用户广播消息有任何想法吗?
【问题讨论】:
-
我遇到了同样的问题,我的快速解决方案(目前)是让每个客户端在页面加载时生成一个“唯一”ID。此 ID 包含在对服务器的所有回调中。当服务器转发消息时,每个客户端都会将此 ID 与其自己的 ID 进行比较,以确定消息是由另一个客户端发送还是由它自己发送(在这种情况下,它将被忽略)。这可能不是最好的解决方案,但它对我有用。