如何在Python中检测BinanceSocketManager websocket断开连接?

Den*_*nis 7 python websocket python-asyncio binance

Binance API 和python-binance提供非阻塞执行的异步功能,如Binance 异步基础知识中所述。

我正在通过 websocket 使用BinanceSocketManager监听(异步非阻塞)实时数据。

在网络间歇性连接丢失等情况下,我希望为我的项目添加自动重新连接功能。但我似乎找不到任何信息BinanceSocketManager。我只能找到一个使用 的指南ThreadedWebsocketManager,但它不是异步实现。

有谁知道如何实现 Binance websocket 断开连接检测和自动重新连接机制?

这是我到目前为止所拥有的一些代码:

import asyncio
from binance import AsyncClient, BinanceSocketManager


async def main():
    client = await AsyncClient.create()
    await kline_listener(client)

async def kline_listener(client):
    bm = BinanceSocketManager(client)
    async with bm.kline_socket(symbol='BTCUSDT') as stream:
        while True:
            res = await stream.recv()
            print(res)
    # a way detect websocket error/disconnect, callback 'disconnect_callback'

async def disconnect_callback():
    await client.close_connection()
    await main()  # restart client and kline socket

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
Run Code Online (Sandbox Code Playgroud)

Wic*_*ear 5

如果其他人正在查看此内容,为此,您应该查看 BinanceAPIException。代码可能看起来像这样:

from binance import AsyncClient, BinanceSocketManager
from binance.exceptions import BinanceAPIException

async def main():

    client = await AsyncClient.create()
    bm = BinanceSocketManager(client, user_timeout=60)

    # start any sockets here, i.e a trade socket
    kline_candles = bm.kline_socket('BNBUSDT', interval=client.KLINE_INTERVAL_1MINUTE)

    # start receiving messages
    try:
        status = await client.get_system_status()
        print(status['msg'])

        async with kline_candles as stream:
            for _ in range(5):
                res = await stream.recv()  # create/await response
                await process_message(msg=res, client=client)  # process message
            
    except BinanceAPIException as e:
        print(e)
        await disconnect_callback(client=client)

async def disconnect_callback(client):
    await client.close_connection()  # close connection
    time.sleep(60)  # wait a minute before restarting
    await main()  # restart client and kline socket

async def process_message(msg, client):
    if msg['e'] == 'error':
        await disconnect_callback(client=client)

        print('ERROR OCCURED')
        
    else:
        candle = msg['k']  # get only the candle info within the general dict

        start_time = datetime.utcfromtimestamp(candle['t']/1000).strftime('%Y-%m-%d %H:%M:%S')
        close_time = datetime.utcfromtimestamp(candle['T']/1000).strftime('%Y-%m-%d %H:%M:%S')

        print(f'__ start: {start_time}, close: {close_time}')
        print(msg)

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
Run Code Online (Sandbox Code Playgroud)

断开连接尚未经过测试,但我认为这会起作用。如果有人有任何补充说明,请告诉我。