当前位置:网站首页>A simple websocket example
A simple websocket example
2022-07-19 11:38:00 【Forever wheat field】
An example of writing , For testing websocket For server
There is an automatic connection part , That is, if you are disconnected from the server , The system will connect again websocket The server , Avoid completely breaking data due to network problems
It should be noted that ,websocket The component must be 0.57.0, The later updated components are no longer followed , It should conflict with the current use .
The complete code is as follows :
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 # Contract code
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": # Real time futures market
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)Run a screenshot :
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"}边栏推荐
- A curated list of awesome Qt and QML
- JVM hook hooks function
- LeetCode刷题——查找和最小的 K 对数字#373#Medium
- 【二叉树】之力扣牛客必刷题
- Solution of connecting MySQL instance with public network
- 热议:老公今年已经34周岁想读博,以后做科研,怎么办?
- 华为无线设备配置频谱导航
- Tier defect detection using full revolutionary network
- Will causal learning open the next generation of AI? Chapter 9 Yunji datacanvas officially released the open source project of ylarn causal learning
- What happened to cinder in openstack-m
猜你喜欢

Unity high version returned low version error

Cv02 Roge matrix, rotation vector, angle

Docker安装MySQL

Hot discussion: my husband is 34 years old this year and wants to read a doctoral degree. What should I do in the future to do scientific research?

To build agile teams, these methods are indispensable

Detailed explanation of MySQL show processlist

机器人开发--常用仿真软件工具

cv02-roge矩阵,旋转向量 ,角度

Deep Learning for Generic Object Detection: A Survey-论文阅读笔记

Performance optimization @contented to reduce pseudo sharing
随机推荐
设置cmd命令提示符窗口的界面语言为英文
Leetcode 1304. N different integers with zero and
Developing those things: how to solve the problem of long-time encoding and decoding of RK chip video processing?
cv02-roge矩阵,旋转向量 ,角度
Unity高版本退回低版本报错问题
Leetcode 1328. 破坏回文串(可以,已解决)
夢想CMS 前臺搜索SQL注入
MySQL autoincrement ID, UUID and snowflake ID
《MySQL DBA封神打怪之路》专栏学习大纲
LeetCode 558. Intersection of quadtree
How to change and reset forgotten root password in RHEL 9
02-3. Difference between pointer and reference
TCP congestion control details | 7 Surpass TCP
Microservice online specification
Hello JSON Schema
A summary of C language pointer
Whether pjudge 21652-[pr 4] has nine [digit DP]
常见分布式锁介绍
Daily question brushing record (26)
02-3、指针和引用的区别