import asyncio
import websockets
import json
async def subscribe_without_login_index(url, channels):
while True:
async with websockets.connect(url) as ws:
sub_param = {"method": "SUBSCRIBE","params":channels,"id": 1}
sub_str = json.dumps(sub_param)
await ws.send(sub_param)
while True:
try:
res_b = await asyncio.wait_for(ws.recv(), timeout=55)
except (asyncio.TimeoutError, websockets.exceptions.ConnectionClosed) as e:
try:
await ws.send('pong')
res_b = await ws.recv()
print(res_b)
except Exception as e:
print("连接关闭,正在重连……")
break
await asyncio.sleep(1)
if 'event' in res_b:
continue
url = 'wss://fstream.binance.com/ws/<!markPrice@arr>'
channels = ["!miniTicker@arr"]
loop = asyncio.get_event_loop()
loop.run_until_complete(subscribe_without_login_index(url, channels))
loop.close()
运行后报错: TimeoutError: [Errno 10060] Connect call failed ('104.244.46.185', 443)。
其中wss接口url: wss://fstream.binance.com/ws/<!markPrice@arr>
订阅一个信息流:
-
请求
{
"method": "SUBSCRIBE",
"params":["!markPrice@arr],
"id": 1
}
我用websocket 网站测试是OK的,如下图所示:
测试网站: https://www.websocket.org/echo.html
但是用python弄不出来,有高手能指点下吗?