Explain several common link methods for python websocket to obtain real time data in detail
- 2021-07-06 11:11:08
- OfStack
The first is to use create_connection link, which requires pip install websocket-client (this method is not recommended, the link is unstable, easy to break, and the connection is time consuming)
import time
from websocket import create_connection
url = 'wss://i.cg.net/wi/ws'
while True: # 1 Links directly and exits the loop until it is connected
time.sleep(2)
try:
ws = create_connection(url)
print(ws)
break
except Exception as e:
print(' Connection exception: ', e)
continue
while True: # Connect, exit the first 1 After three loops, this loop is used for 1 Direct access to data
ws.send('{"event":"subscribe", "channel":"btc_usdt.ticker"}')
response = ws.recv()
print(response)
Second, the operation effect is very good, it is easy to connect, and the speed of obtaining data is also very fast
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()
The third kind, in fact, is similar to the first kind, but it is written in a different way. The running effect is not ideal, the connection is time-consuming, and it is easy to break
import websocket
while True:
ws = websocket.WebSocket()
try:
ws.connect("wss://i.cg.net/wi/ws")
print(ws)
break
except Exception as e:
print(' Exception: ', e)
continue
print('OK')
while True:
req = '{"event":"subscribe", "channel":"btc_usdt.deep"}'
ws.send(req)
resp = ws.recv()
print(resp)
The fourth, the running effect can also, run_forever has many parameters, need to set their own
import websocket
def on_message(ws, message): # When the server has data update, it actively pushes the data
print(message)
def on_error(ws, error): # When the program reports an error, it will trigger on_error Events
print(error)
def on_close(ws):
print("Connection closed ... ")
def on_open(ws): # Triggered after connecting to the server on_open Event, which is used here for send Data
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)