类之间的Python异步通信
我实现了一个类,该类连接到websocket以接收异步消息类之间的Python异步通信,python,websocket,twisted,coroutine,gevent,Python,Websocket,Twisted,Coroutine,Gevent,我实现了一个类,该类连接到websocket以接收异步消息 class websocketClient(...): def on_message(self, msg): # Gets automatically called notifyBrokerAbout(msg) # How to proceed from here? class Broker(): self.websocket = websocketClient(...) self.webs
class websocketClient(...):
def on_message(self, msg): # Gets automatically called
notifyBrokerAbout(msg) # How to proceed from here?
class Broker():
self.websocket = websocketClient(...)
self.websocket.start()
def heartbeat(self):
return self.websocket
heartbeat函数启动websocket并返回它。websocket类本身有一个on_message()
函数,该函数充当回调函数,每次收到新消息时都会触发该回调函数
我不想不时调用函数从websocket中获取最新的msg
,而是希望在on_message()中到达后,将这些消息推送到代理中
如何用Python最好地解决这个问题?我正在寻找一种方法,将来自websocketClient
s的新消息推送到heartbeat()
,这样在主应用程序中,我可以订阅该函数并等待更新。这可以通过reactor模式(异步处理请求)来解决,然后是同步调度
通过搜索“reactor gevent”和“reactor twisted”,您将找到许多好的示例。有几种变体。我将避免推荐特定的变体,因为总体选择将取决于示例代码中不明显的其他系统级问题
broker = Broker()
hearbeats = broker.heartbeat()
for beat in heartbeats:
...