我在websockets方面没有太多经验,但我有一个websocket客户。
但是,我有一个计算结果的函数,时间t的结果取决于时间t-1的结果和新消息。因此,我需要确保websockets处理信息的顺序与消息到达的顺序相同。我该如何实现?Websocket客户端是0.48版和Python3.7版。
这是我的代码片段:
import websocket
import threading
class MyWebsocket():
def __init__(self):
self.endpoint = 'endpoint'
self.result = {} # start with an empty dict
def __connect(self):
'''Connect to the websocket in a thread.'''
self.ws = websocket.WebSocketApp(self.endpoint,
on_open=self.__on_open,
on_message=self.__on_message)
self.wst = threading.Thread(target=lambda: self.ws.run_forever())
self.wst.daemon = True
self.wst.start()
def __on_open(self, ws):
login_str = 'string'
ws.send(login_str)
def __on_message(self, ws, message):
result = foo(message, self.result) # calculate result out of the message and the previous result
self.result = result # make class result equal to calculated result so that next thread can access it
ws = MyWebsocket()