当前位置:   article > 正文

Python: 几种websocket的链接方式_from websocket import create_connection

from websocket import create_connection

转载:https://blog.csdn.net/Darkman_EX/article/details/82592118

第一种, 使用create_connection链接,需要pip install websocket-client (此方法不建议使用,链接不稳定,容易断,并且连接很耗时)

  1. import time
  2. from websocket import create_connection
  3. url = 'wss://i.cg.net/wi/ws'
  4. while True: # 一直链接,直到连接上就退出循环
  5. time.sleep(2)
  6. try:
  7. ws = create_connection(url)
  8. print(ws)
  9. break
  10. except Exception as e:
  11. print('连接异常:', e)
  12. continue
  13. while True: # 连接上,退出第一个循环之后,此循环用于一直获取数据
  14. ws.send('{"event":"subscribe", "channel":"btc_usdt.ticker"}')
  15. response = ws.recv()
  16. print(response)

第二种,运行效果很不错,很容易连接,获取数据的速度也挺快

  1. import json
  2. from ws4py.client.threadedclient import WebSocketClient
  3. class CG_Client(WebSocketClient):
  4. def opened(self):
  5. req = '{"event":"subscribe", "channel":"eth_usdt.deep"}'
  6. self.send(req)
  7. def closed(self, code, reason=None):
  8. print("Closed down:", code, reason)
  9. def received_message(self, resp):
  10. resp = json.loads(str(resp))
  11. data = resp['data']
  12. if type(data) is dict:
  13. ask = data['asks'][0]
  14. print('Ask:', ask)
  15. bid = data['bids'][0]
  16. print('Bid:', bid)
  17. if __name__ == '__main__':
  18. ws = None
  19. try:
  20. ws = CG_Client('wss://i.cg.net/wi/ws')
  21. ws.connect()
  22. ws.run_forever()
  23. except KeyboardInterrupt:
  24. ws.close()

第三种,其实和第一种差不多,只不过换种写法而已,运行效果不理想,连接耗时,并且容易断

  1. import websocket
  2. while True:
  3. ws = websocket.WebSocket()
  4. try:
  5. ws.connect("wss://i.cg.net/wi/ws")
  6. print(ws)
  7. break
  8. except Exception as e:
  9. print('异常:', e)
  10. continue
  11. print('OK')
  12. while True:
  13. req = '{"event":"subscribe", "channel":"btc_usdt.deep"}'
  14. ws.send(req)
  15. resp = ws.recv()
  16. print(resp)

第四种,运行效果也可以,run_forever里面有许多参数,需要自己设置

  1. import websocket
  2. def on_message(ws, message): # 服务器有数据更新时,主动推送过来的数据
  3. print(message)
  4. def on_error(ws, error): # 程序报错时,就会触发on_error事件
  5. print(error)
  6. def on_close(ws):
  7. print("Connection closed ……")
  8. def on_open(ws): # 连接到服务器之后就会触发on_open事件,这里用于send数据
  9. req = '{"event":"subscribe", "channel":"btc_usdt.deep"}'
  10. print(req)
  11. ws.send(req)
  12. if __name__ == "__main__":
  13. websocket.enableTrace(True)
  14. ws = websocket.WebSocketApp("wss://i.cg.net/wi/ws",
  15. on_message=on_message,
  16. on_error=on_error,
  17. on_close=on_close)
  18. ws.on_open = on_open
  19. ws.run_forever(ping_timeout=30)

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/85480
推荐阅读
相关标签
  

闽ICP备14008679号