gevent-socketio 如何从服务器发起消息
gevent-socketio how to originate messages from server
这是我的代码:
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
中做到这一点,但它对我的口味来说太神奇了。是否有较低级别的实现?
您必须将所有 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'
这是我的代码:
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
中做到这一点,但它对我的口味来说太神奇了。是否有较低级别的实现?
您必须将所有 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'