详解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设计】。

相关文章

基于python3 的百度图片下载器的实现代码

自己写了玩的一个小脚本,百度图片下载 import re import os import requests import hashlib def dowmloadPic(h...

python与C互相调用的方法详解

前言 最近因为工作的需要,在考虑基于udp做一个用于网游战斗中的数据同步协议,为了前期测试数据,决定先做一个外部的代理tunnel,原理是在server端和client端分别建立网络转发...

实例分析python3实现并发访问水平切分表

场景说明 假设有一个mysql表被水平切分,分散到多个host中,每个host拥有n个切分表。 如果需要并发去访问这些表,快速得到查询结果, 应该怎么做呢? 这里提供一种方案,...

Python异常处理例题整理

Python异常处理例题整理

什么是异常? 异常是Python对象,表示一个错误。当Python脚本发生异常时我们需要捕获处理它,否则程序会终止执行。在程序运行过程中,总会遇到各种各样的错误,有的错误是程序编写有问题...

Python进阶之自定义对象实现切片功能

切片是 Python 中最迷人最强大最 Amazing 的语言特性(几乎没有之一),在《Python进阶:切片的误区与高级用法》中,我介绍了切片的基础用法、高级用法以及一些使用误区。这些...