详解python websocket获取实时数据的几种常见链接方式

作者:Jerry_JD 时间:2023-09-20 08:22:23 

第一种, 使用create_connection链接,需要pip install websocket-client (此方法不建议使用,链接不稳定,容易断,并且连接很耗时)


import time
from websocket import create_connection

url = 'wss://i.cg.net/wi/ws'
while True: # 一直链接,直到连接上就退出循环
 time.sleep(2)
 try:
   ws = create_connection(url)
   print(ws)
   break
 except Exception as e:
   print('连接异常:', e)
   continue
while True: # 连接上,退出第一个循环之后,此循环用于一直获取数据
 ws.send('{"event":"subscribe", "channel":"btc_usdt.ticker"}')
 response = ws.recv()
 print(response)

第二种,运行效果很不错,很容易连接,获取数据的速度也挺快


import json
from ws4py.client.threadedclient import WebSocketClient

class CG_Client(WebSocketClient):

def opened(self):
   req = '{"event":"subscribe", "channel":"eth_usdt.deep"}'
   self.send(req)

def closed(self, code, reason=None):
   print("Closed down:", code, reason)

def received_message(self, resp):
   resp = json.loads(str(resp))
   data = resp['data']
   if type(data) is dict:
     ask = data['asks'][0]
     print('Ask:', ask)
     bid = data['bids'][0]
     print('Bid:', bid)

if __name__ == '__main__':
 ws = None
 try:
   ws = CG_Client('wss://i.cg.net/wi/ws')
   ws.connect()
   ws.run_forever()
 except KeyboardInterrupt:
   ws.close()

第三种,其实和第一种差不多,只不过换种写法而已,运行效果不理想,连接耗时,并且容易断


import websocket

while True:
 ws = websocket.WebSocket()
 try:
   ws.connect("wss://i.cg.net/wi/ws")
   print(ws)
   break
 except Exception as e:
   print('异常:', e)
   continue
print('OK')
while True:
 req = '{"event":"subscribe", "channel":"btc_usdt.deep"}'
 ws.send(req)
 resp = ws.recv()
 print(resp)

第四种,运行效果也可以,run_forever里面有许多参数,需要自己设置


import websocket

def on_message(ws, message): # 服务器有数据更新时,主动推送过来的数据
 print(message)

def on_error(ws, error): # 程序报错时,就会触发on_error事件
 print(error)

def on_close(ws):
 print("Connection closed ……")

def on_open(ws): # 连接到服务器之后就会触发on_open事件,这里用于send数据
 req = '{"event":"subscribe", "channel":"btc_usdt.deep"}'
 print(req)
 ws.send(req)

if __name__ == "__main__":
 websocket.enableTrace(True)
 ws = websocket.WebSocketApp("wss://i.cg.net/wi/ws",
               on_message=on_message,
               on_error=on_error,
               on_close=on_close)
 ws.on_open = on_open
 ws.run_forever(ping_timeout=30)

来源:https://blog.csdn.net/Darkman_EX/article/details/82592118

标签:python,websocket,链接
0
投稿

猜你喜欢

  • 对numpy中array和asarray的区别详解

    2022-06-26 04:40:12
  • 在页面中输出当前客户端时间javascript实例代码

    2024-02-25 23:07:56
  • python网络爬虫精解之pyquery的使用说明

    2021-05-28 13:01:19
  • SQL Server上进行表设计时表的主键设计问题

    2010-06-24 16:10:00
  • Docker构建python Flask+ nginx+uwsgi容器

    2023-07-25 06:36:43
  • JavaScript使用正则表达式获取全部分组内容的方法示例

    2023-08-27 13:38:18
  • D3.js实现绘制折线图的教程详解

    2024-04-10 10:53:54
  • Python 中的 Counter 模块及使用详解(搞定重复计数)

    2022-08-22 15:46:17
  • windows下python虚拟环境virtualenv安装和使用详解

    2023-08-30 11:06:39
  • js 删除数组的几种方法小结

    2024-04-22 22:42:37
  • MySql树形结构(多级菜单)查询设计方案

    2024-01-18 15:35:42
  • python+pyqt实现右下角弹出框

    2023-09-07 16:04:22
  • vue.js 自定义指令(拖拽、拖动、移动) 指令 v-drag详解

    2024-05-28 15:55:24
  • [JS效果]动画效果打开/关闭/移动层

    2008-04-10 11:42:00
  • pytorch 自定义参数不更新方式

    2021-11-11 01:55:55
  • CentOS6.5下RPM方式安装mysql5.6.33的详细教程

    2024-01-23 12:43:02
  • python编程简单几行代码实现视频转换Gif示例

    2021-09-02 03:34:13
  • Web跨浏览器进程通信(Web跨域)

    2024-05-02 16:20:02
  • django 外键model的互相读取方法

    2021-06-16 20:54:51
  • Python程序员开发中常犯的10个错误

    2023-12-14 04:56:32
  • asp之家 网络编程 m.aspxhome.com