写的一个范例,用来测试websocket服务器用的
有自动连接部分,即如果与服务器断开,系统会再次连接websocket服务器,避免因网络问题引发数据彻底断了
需要注意的是,websocket组件必须是0.57.0,后面更新的组件没有再跟了,应该与当前的使用有冲突。
完整代码如下:
import websocket # websocket_client==0.57.0
import queue
import json
import time
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://192.168.1.100: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=[])
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)
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)
运行截图:
D:\ProgramData\Anaconda3\envs\pydev3.9\python.exe E:/work/py/strategyserver/strategyserver/websocketclient_demo2.py rb2210
## sys.argv:{} ['E:/work/py/strategyserver/strategyserver/websocketclient_demo2.py', 'rb2210']
##: @@@ In JOB @@@:{} rb2210
### on_open: {} rb2210
deal_data.......begin
# Subscribe Msg: {} {"symbols":"rb2210","subscribe":"on"}