我正在尝试同时连接到多个通道,并通过 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()
Use partial传递附加参数
from functools import partial
def on_open(ws, channel_name):
"""
Notice the channel_name parameter
"""
# create a new function with the predefined variable
chan1 = partial(on_open, channel_name='channel 1')
# set the new function as the on_open callback
ws1.on_open = chan1
# do the same for the rest
chan2 = partial(on_open, channel_name='channel 2')
ws2.on_open = chan2
作为旁注,考虑使用Tornado or Crossbar.io (aka autobahn
)。这些是正确的异步框架,与线程和多处理相比,它们使 Websocket 开发更简单。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)