python一个简单的websocketclient的示例程序

374 阅读1分钟

程序假设有一websocket服务器,然后我们将数据收过来,为了防止数据处理时丢失数据,可以使用队列,然后异步处理。 关于处理这一块``` def deal_data(self):

这个必须是当前的连接已经开始了才工作,连接结束了应该也随着销毁,因此,程序中需要不断检测ws连接是否有效,没有连接这个过程就应该退出去。

程序比较简单,直接上代码:

```python
import websocket    # websocket_client==0.57.0
import queue
import json
import time
import datetime
import sys
from apscheduler.schedulers.background import BackgroundScheduler

try:
    import thread
except ImportError:
    import _thread as thread


class RecvTickWebSocket:

    def __init__(self, _instrument_id):
        self._instrument_id = _instrument_id  # 合约代码
        self.ws: websocket.WebSocketApp = None
        self.queue = queue.Queue()
        self.url = "ws://127.0.0.1:9001/ws"

    def get_ws_status(self, ws: websocket.WebSocketApp):
        if self is None or ws is None:
            return False
        return ws.sock is not None

    def deal_data(self):
        print("deal_data.......begin")
        ws = self.ws
        while self.get_ws_status(ws):
            time_out = False
            tick_data: dict = None
            try:
                tick_data = self.queue.get(timeout=3)
            except Exception:
                time_out = True

            if not time_out:
                print(tick_data)
        print("###:[{}] deal_data end", self._instrument_id)


    def __del__(self):
        if self.ws is not None:
            print("####: Close WS")
            self.ws.close()

    @property
    def instrument_id(self):
        return self._instrument_id

    def on_message(self, message):
        data = json.loads(message)
        if "dataType" in data and data["dataType"] == "future_depth":  # 期货实时行情
            self.queue.put(data)

    def on_error(self, error):
        print("####### on_error #######,[{}]: {}", self._instrument_id, error)

    def on_close(self):
        pass

    def on_open(self):
        print("### on_open: {}", self.instrument_id)
        scheduler = BackgroundScheduler()
        scheduler.add_job(self.deal_data, args=[self._instrument_id])
        scheduler.start()

        def run(*args):
            msg = '{{"symbols":"{}","subscribe":"on"}}'.format(self.instrument_id)
            print("# Subscribe Msg: {}", msg)
            self.ws.send(msg)
        thread.start_new_thread(run, ())

    def start(self):
        self.ws = websocket.WebSocketApp(self.url,
                                         on_message=self.on_message,
                                         on_error=self.on_error,
                                         on_close=self.on_close)
        self.ws.on_open = self.on_open
        self.ws.run_forever(ping_interval=60, ping_timeout=5)

    @staticmethod
    def job(instrument_id):
        print("##: @@@ In JOB @@@:{}", instrument_id)
        my_web = RecvTickWebSocket(instrument_id)
        while True:
            my_web.start()
            time.sleep(1)

    @staticmethod
    def strategy_job(self):
        print("##: @@@ In strategy_job @@@")
        while True:
            data = self.queue.get()
            print(data)
            # exit(0)


def do_recv_contract(instrument_id):
    sched = BackgroundScheduler()
    sched.add_job(RecvTickWebSocket.job, args=[instrument_id])
    sched.start()
    while True:
        time.sleep(1)

if __name__ == '__main__':
    argv = sys.argv
    instrument_id = argv[1]
    print("## sys.argv:{}", argv)
    do_recv_contract(instrument_id)