簡體   English   中英

如何將從 websocket 接收到的 on_message 數據返回到類外部? 使用 python websocket-client

[英]How to return on_message data received from websocket to outside of the class? Using python websocket-client

我試圖讓我的代碼從 Websocket 連接中獲取一些數據,然后使用來自 WS 響應的數據。 問題是,我不知道如何讓代碼等待 WS 回答,然后將數據“發送”到 WS 類之外。

我正在使用這個 websocket-client lib ( https://github.com/websocket-client/websocket-client ) 並使用該頁面中的“長期連接”示例。

import websocket
import _thread as thread
import time, json

class Frame:
  def __init__(self):
    self.m = 0 
    self.i = 0 
    self.n = ""
    self.o = ""

class MyWS():
    def __init__(self):
        self.wsadd = 'ws://websocket.org/' #Example 
        self.frame = Frame()

        self.openWS()

    def on_message(self, message):
        msg = json.loads(message)
        print(msg)
        if msg["n"] == 'SubscribeData':
            self.sub = json.loads(msg['o'])
            return self.sub #It doesn't seem to do anything

    def on_error(self, error):
        print(error)

    def on_close(self):
        print("WS closed")

    def on_open(self):
        def run(*args):
            print('WS Open')
            #self.Authenticate() #Commented because haven't code it yet
            #self.sendWS()
            thread.start_new_thread(run, ())

    def openWS(self):
        websocket.enableTrace(True)
        self.ws = websocket.WebSocketApp(self.wsadd, on_message = self.on_message, on_open = self.on_open, on_error = self.on_error, on_close = self.on_close)
        self.wst = threading.Thread(target=lambda: self.ws.run_forever())
        self.wst.daemon = True
        self.wst.start()

    def sendWS(self):
        self.ws.send(json.dumps(self.frame.__dict__))


    def SubscribeData(self):
        self.frame.m = 0
        self.frame.i = int(time.time())
        self.frame.n = 'SubscribeData'
        payload = {
            "OMSId": 1,
            "InstrumentId": 1,
            }
        self.frame.o = json.dumps(payload)
        self.sendWS(self.frame)
        #return #Should return something here?

obj = MyWS() #When the obj is instantiated the WS Connection is opened.

result = obj.SubscribeData() #This sends a request for subscribing to the datafeed. It get's an answer but isn't saved in the variable. (because the method doesn't really return anything)

print(result) #prints None

當我實例化MyWS類時,WS 連接是開放的。

當我使用SubscibeData方法時,我得到了預期的響應。 所以 websocket 部分工作正常。

on_message方法將響應保存在self.sub但不會在任何地方返回。

我真正需要的是一種將接收到的數據發送到“外部”類的方法,因此“外部代碼”不僅等待接收數據,還可以對其進行操作

我對 websockets 很陌生,所以你知道......

要回答@HJA24 以及還有誰可能會偶然發現這個問題,我並沒有真正找到一個(好的)解決方案,但做了一個解決方法。

由於on_message方法將返回值保存在self.sub我創建了另一個返回self.sub值的self.sub ,這樣我就可以訪問 WS 響應。 如果您決定采用此方法,則必須考慮到這樣一個事實,即 WS 回答您的時間可能比您調用返回值的方法所需的時間更長。

像這樣的東西:

import websocket
import ...

class MyWS():
    def __init__(self):
        self.wsadd = 'ws://websocket.org/' #Example 
        self.frame = Frame()
        self.openWS()

    def on_message(self, message):
        msg = json.loads(message)
        if msg["n"] == 'SubscribeData':
            self.sub = json.loads(msg['o'])

    def get_subscribe_data(self):
        return self.sub

    def on_error(self, error):
        ...

obj = MyWS() #When the obj is instantiated the WS Connection is opened.

obj.SubscribeData()
result = obj.get_subscribe_data()
print(result) #prints the data on self.sub

我不接受我自己的答案,因為肯定有更好的方法來做到這一點,所以如果您正在閱讀本文並有想法,請隨時分享。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM