这是我的代码:
class FirstNamespace(BaseNamespace):
def on_some_event(self, msg):
self.emit('ok '+msg)
@app.route('/socket.io/<path:remaining>') # socket.io endpoint
def socketio_withpath(remaining):
socketio_manage(request.environ,
{'/channel1': FirstNamespace}
return 'ok'
@app.route('/dosomething/', methods=['POST']) # simple http endpoint
def dosomething():
data = request.form
# ...
# some code that triggers self.emit from within FirstNamespace
# ...
return 'data processed'
我很乐意从前端发送套接字消息,它们会得到处理,我会收到on_some_event
方法的回复。
问题是,如果我自己先发一条消息,我只会收到一条消息。
但是,如何在不成为第一个交谈的情况下开始接收消息?
例如,如果有人向/dosomething/
端点发送POST,它如何触发emit
到我的客户端websocket?
-
我可以在flask-socketio
中做到这一点,但它对我的品味有太大的魔力。是否有较低级别的实现?
答案 0 :(得分:0)
您必须收集集合中的所有channel1-Connections,然后才能向所有连接发送消息:
from weakref import WeakSet
class FirstNamespace(BaseNamespace):
connections = WeakSet()
def initialize(self):
self.connections.add(self)
def on_some_event(self, msg):
self.emit('ok '+msg)
@app.route('/socket.io/<path:remaining>') # socket.io endpoint
def socketio_withpath(remaining):
socketio_manage(request.environ,
{'/channel1': FirstNamespace}
return 'ok'
@app.route('/dosomething/', methods=['POST']) # simple http endpoint
def dosomething():
data = request.form
for conn in FirstNamespace.connections:
conn.emit("response_channel", data)
return 'data processed'