websocket获取实时数据的几种常见链接方式。第一种, 使用create_connection链接,需要pip install websocket-client (此方法不建议使用,链接不稳定,容易断,并且连接很耗时),,第二种,运行效果很不错,很容易连接,获取数据的速度也挺快,第三种,其实和第一种差不多,只不过换种写法而已,运行效果不理想,连接耗时,并且容易断,第四种,运行效果也可以,run_forever里面有许多参数,需要自己设置
第一种, 使用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()
第四种,运行效果也可以,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)
相关文章:
-
-
websocket连接上了300以后jvm就报内存溢出了,把jvm溢出的堆栈日志导了出来这是详情: 648 instances of "org.apache.tomcat.webs…
-
-
-
-
版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。
发表评论