【问题标题】:Python websockets, subscribe to multiple channelsPython websockets,订阅多个频道
【发布时间】: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


    【解决方案1】:

    使用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
    

    作为旁注,请考虑使用TornadoCrossbar.io(又名autobahn)。这些是适当的异步框架,与线程和多处理相比,使 websocket 开发更简单。

    【讨论】:

      猜你喜欢
      • 2013-05-01
      • 2019-08-06
      • 1970-01-01
      • 1970-01-01
      • 2022-06-11
      • 1970-01-01
      • 2018-06-20
      • 1970-01-01
      • 2017-10-08
      相关资源
      最近更新 更多