python: websocket獲取實時資料的幾種常見連結方式
阿新 • • 發佈:2019-01-03
第一種, 使用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)