没有合适的资源?快使用搜索试试~ 我知道了~
首页详解python websocket获取实时数据的几种常见链接方式
第一种, 使用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
资源详情
资源评论
资源推荐

详解详解python websocket获取实时数据的几种常见链接方式获取实时数据的几种常见链接方式
第一种, 使用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:


















安全验证
文档复制为VIP权益,开通VIP直接复制

评论0