我正在尝试同时连接到多个通道,并通过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()