【发布时间】:2017-12-02 21:21:17
【问题描述】:
我正在学习将 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 使用的 CPU 似乎比 pusherclient 少很多。由于我需要同时打开多个客户端,我真的很想节省资源。我在想应该有一种比while True 循环更好、更漂亮、更便宜的方式来让套接字保持活动状态。有谁知道好的技术吗?
谢谢
【问题讨论】:
-
不清楚您的目标是什么,以及会发生什么。套接字是否正在关闭?也不清楚您使用的是什么库 - 听起来您正在使用两个不同的库作为客户端连接到 Pusher。
-
感谢 cmets,我想这不是很清楚。我正在使用 2 个库同时连接到 2 个(或更多)websocket 提要。我想这不是一个好问题,我想我会关闭它。
标签: python sockets websocket pusher