第一種, 使用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)
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

