Pusher on Python永远运行

时间:2017-06-29 09:00:47

标签: python sockets websocket pusher

我正在学习使用websockets进行新项目。我想监视来自多个不同套接字连接的实时消息流。恰好,其中一个套接字API使用Pusher。我喜欢在python中工作,所以我找到了the pusherclient pacakge on pypi。对于我使用the websocket-client package的其他连接。

所以我遇到的问题是,除了示例中的while True:循环之外,还有更好的方法让推送客户端永远运行:

...
global pusher

# We can't subscribe until we've connected, so we use a callback handler
# to subscribe when able
def connect_handler(data):
    channel = pusher.subscribe('mychannel')
    channel.bind('myevent', callback)

pusher = pusherclient.Pusher(appkey)
pusher.connection.bind('pusher:connection_established', connect_handler)
pusher.connect()

while True:
    # Do other things in the meantime here...
    time.sleep(1)

这可行,但似乎真的很糟糕的CPU。使用websocket-client包,pypi页面上有一个示例,显示如何永久运行客户端:

...
#omitted function definitions
if __name__ == "__main__":
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp("ws://echo.websocket.org/",
                              on_message = on_message,
                              on_error = on_error,
                              on_close = on_close)
    ws.on_open = on_open
    ws.run_forever()

我测试了两种类型的代码,但它们都有效,但websocket-client似乎比pusherclient使用的CPU少得多。由于我需要同时打开多个客户端,我真的想节省资源。我认为应该有一个比while True循环更好,更漂亮,更有希望让套接字保持活力的方法。有谁知道一个好的技术?

由于

1 个答案:

答案 0 :(得分:0)

默认情况下,Pusher客户端是一个守护进程,这意味着基础线程在后台运行,并且不会阻止python主线程关闭。

至少在较新的版本(例如:0.6.0b2)中,有一个名为daemon的初始化参数,您可以将其设置为False,这样您就不必保留在{{ 1}}循环。

示例:

while