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

yipeiwu_com5年前Python基础

第一种, 使用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)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python占位符输入方式实例

占位符,顾名思义就是插在输出里站位的符号。占位符是绝大部分编程语言都存在的语法, 而且大部分都是相通的, 它是一种非常常用的字符串格式化的方式。 1、常用占位符的含义 s : 获取传入...

python实现kMeans算法

聚类是一种无监督的学习,将相似的对象放到同一簇中,有点像是全自动分类,簇内的对象越相似,簇间的对象差别越大,则聚类效果越好。 1、k均值聚类算法 k均值聚类将数据分为k个簇,每个簇通...

python中多个装饰器的执行顺序详解

python中多个装饰器的执行顺序详解

装饰器是程序开发中经常会用到的一个功能,也是python语言开发的基础知识,如果能够在程序中合理的使用装饰器,不仅可以提高开发效率,而且可以让写的代码看上去显的高大上^_^ 使用场景...

python决策树之C4.5算法详解

python决策树之C4.5算法详解

本文为大家分享了决策树之C4.5算法,供大家参考,具体内容如下 1. C4.5算法简介   C4.5算法是用于生成决策树的一种经典算法,是ID3算法的一种延伸...

pytorch逐元素比较tensor大小实例

如下所示: import torch a = torch.tensor([[0.01, 0.011], [0.009, 0.9]]) mask = a.gt(0.01) print(...