如何在多个线程中打开多个websockets并同时运行它们

时间:2017-12-20 20:51:05

标签: python concurrency websocket

我有这个代码从Gdax读取消息,我现在要做的是启动一个新线程,从另一个交换机读取来自另一个websocket的消息并同时运行。我该怎么做?

import websocket
from json import dumps, loads
try:
    import thread
except ImportError:
    import _thread as thread

def on_message(ws, message):
    parsed_msg = loads(message)
    print(parsed_msg["product_id"], parsed_msg["price"])

def on_open(ws):
    def run(*args):
        params = {
            "type": "subscribe",
            "channels": [{"name": "ticker", "product_ids": ["BTC-USD", 
"ETH-USD"]}]
        }
        ws.send(dumps(params))
    thread.start_new_thread(run, ())

if __name__ == "__main__":
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp("wss://ws-feed.gdax.com", on_open=on_open, 
on_message = on_message)
    ws.run_forever()

0 个答案:

没有答案