【发布时间】:2018-01-20 14:25:19
【问题描述】:
我正在尝试同时连接到多个通道并通过 python websocket 库从推送 API 接收消息。
考虑到以下代码,您将如何连接到多个通道?这段代码是从这里获得并稍作修改的:https://pypi.python.org/pypi/websocket-client
让我感到困惑的是倒数第二行:ws.on_open = on_open。 on_open 被定义为上面的一个函数,并接受 1 个参数,但在调用该函数时没有传递任何参数,我不记得以前在 python 代码中遇到过这个,所以我不确定这一行到底发生了什么。
如何修改此代码,以便将包含字符串的变量传递给函数 on_open,以便指定要订阅的 Chanel 的名称?我的主要目标是能够使用多处理库传递多个频道以同时订阅。
我是否可以通过创建多个 ws 对象或一个 ws 对象并使用不同的通道作为参数多次调用 on_open 来实现这一点?
import websocket
import thread
import time
import json
def on_message(ws, message):
print(message)
def on_error(ws, error):
print(error)
def on_close(ws):
print("### closed ###")
def on_open(ws):
def run(*args):
ws.send(json.dumps({'channel':'channel1'}))
while True:
time.sleep(1)
ws.close()
print("thread terminating...")
thread.start_new_thread(run, ())
if __name__ == "__main__":
websocket.enableTrace(True)
ws = websocket.WebSocketApp("wss://random.example.com",
on_message = on_message,
on_error = on_error,
on_close = on_close)
ws.on_open = on_open
ws.run_forever()
【问题讨论】:
标签: python websocket multiprocessing wamp