詳解python websocket獲取實(shí)時數(shù)據(jù)的幾種常見鏈接方式
第一種, 使用create_connection鏈接,需要pip install websocket-client (此方法不建議使用,鏈接不穩(wěn)定,容易斷,并且連接很耗時)
import time
from websocket import create_connection
url = 'wss://i.cg.net/wi/ws'
while True: # 一直鏈接,直到連接上就退出循環(huán)
time.sleep(2)
try:
ws = create_connection(url)
print(ws)
break
except Exception as e:
print('連接異常:', e)
continue
while True: # 連接上,退出第一個循環(huán)之后,此循環(huán)用于一直獲取數(shù)據(jù)
ws.send('{"event":"subscribe", "channel":"btc_usdt.ticker"}')
response = ws.recv()
print(response)
第二種,運(yùn)行效果很不錯,很容易連接,獲取數(shù)據(jù)的速度也挺快
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()
第三種,其實(shí)和第一種差不多,只不過換種寫法而已,運(yùn)行效果不理想,連接耗時,并且容易斷
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)
第四種,運(yùn)行效果也可以,run_forever里面有許多參數(shù),需要自己設(shè)置
import websocket
def on_message(ws, message): # 服務(wù)器有數(shù)據(jù)更新時,主動推送過來的數(shù)據(jù)
print(message)
def on_error(ws, error): # 程序報錯時,就會觸發(fā)on_error事件
print(error)
def on_close(ws):
print("Connection closed ……")
def on_open(ws): # 連接到服務(wù)器之后就會觸發(fā)on_open事件,這里用于send數(shù)據(jù)
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)
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python入門及進(jìn)階筆記 Python 內(nèi)置函數(shù)小結(jié)
這篇文章主要介紹了Python的內(nèi)置函數(shù)小結(jié),需要的朋友可以參考下2014-08-08
keras實(shí)現(xiàn)VGG16 CIFAR10數(shù)據(jù)集方式
這篇文章主要介紹了keras實(shí)現(xiàn)VGG16 CIFAR10數(shù)據(jù)集方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07
解決pip install中UnicodeDecodeError問題的處理
這篇文章主要介紹了解決pip install中UnicodeDecodeError問題的處理,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-09-09
PyTorch學(xué)習(xí):動態(tài)圖和靜態(tài)圖的例子
今天小編就為大家分享一篇PyTorch學(xué)習(xí):動態(tài)圖和靜態(tài)圖的例子,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01
Tensorflow 如何從checkpoint文件中加載變量名和變量值
這篇文章主要介紹了Tensorflow 如何從checkpoint文件中加載變量名和變量值的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-05-05
Python基于SMTP協(xié)議實(shí)現(xiàn)發(fā)送郵件功能詳解
這篇文章主要介紹了Python基于SMTP協(xié)議實(shí)現(xiàn)發(fā)送郵件功能,結(jié)合實(shí)例形式分析了Python使用SMTP協(xié)議實(shí)現(xiàn)郵件發(fā)送的相關(guān)操作技巧,并總結(jié)分析了Python發(fā)送純文本郵件、郵件附件、圖片郵件等相關(guān)操作技巧,需要的朋友可以參考下2018-08-08

