Websockets как перестраховаться от потери соединения

Baxudo

Новичок
Пользователь
Июн 6, 2021
14
0
1
Операционная система - Windows 10. Версия python - 3.9.5. Версия библиотек - websockets==9.1 , async-timeout==3.0.1. Подключаюсь к потоку, но из-за ненадежного интернета бывают обрывы связи и получаю ошибку, которую указал снизу. Хочу узнать, как повторно подключаться к потоку если идет ошибка, потому что интернет отключается на кротчайший срок.
Python:
import websockets
import asyncio
import time
import json


async def main():
    url = "wss://stream.binance.com:9443/stream?streams=btcrub@miniTicker"
    async with websockets.connect(url) as client:
        while True:
            data = json.loads(await client.recv())['data']
            event_time = time.localtime(data['E'] // 1000)
            event_time = f"{event_time.tm_hour}:{event_time.tm_min}:{event_time.tm_sec}"
            price = float(data['c'])
            print(event_time, ' ', price)
            print('')

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())


Error in data transfer
Traceback (most recent call last):
File "C:\Users\Alexander\AppData\Local\Programs\Python\Python39\lib\site-packages\websockets\legacy\protocol.py", line 750, in transfer_data
message = await self.read_message()
File "C:\Users\Alexander\AppData\Local\Programs\Python\Python39\lib\site-packages\websockets\legacy\protocol.py", line 819, in read_message
frame = await self.read_data_frame(max_size=self.max_size)
File "C:\Users\Alexander\AppData\Local\Programs\Python\Python39\lib\site-packages\websockets\legacy\protocol.py", line 895, in read_data_frame
frame = await self.read_frame(max_size)
File "C:\Users\Alexander\AppData\Local\Programs\Python\Python39\lib\site-packages\websockets\legacy\protocol.py", line 971, in read_frame
frame = await Frame.read(
File "C:\Users\Alexander\AppData\Local\Programs\Python\Python39\lib\site-packages\websockets\legacy\framing.py", line 55, in read
data = await reader(2)
File "C:\Users\Alexander\AppData\Local\Programs\Python\Python39\lib\asyncio\streams.py", line 723, in readexactly
await self._wait_for_data('readexactly')
File "C:\Users\Alexander\AppData\Local\Programs\Python\Python39\lib\asyncio\streams.py", line 517, in _wait_for_data
await self._waiter
File "C:\Users\Alexander\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 280, in _loop_reading
data = fut.result()
File "C:\Users\Alexander\AppData\Local\Programs\Python\Python39\lib\asyncio\windows_events.py", line 812, in _poll
value = callback(transferred, key, ov)
File "C:\Users\Alexander\AppData\Local\Programs\Python\Python39\lib\asyncio\windows_events.py", line 457, in finish_recv
return ov.getresult()
FileNotFoundError: [WinError 53] Не найден сетевой путь
Traceback (most recent call last):
File "C:\Users\Alexander\AppData\Local\Programs\Python\Python39\lib\site-packages\websockets\legacy\protocol.py", line 750, in transfer_data
message = await self.read_message()
File "C:\Users\Alexander\AppData\Local\Programs\Python\Python39\lib\site-packages\websockets\legacy\protocol.py", line 819, in read_message
frame = await self.read_data_frame(max_size=self.max_size)
File "C:\Users\Alexander\AppData\Local\Programs\Python\Python39\lib\site-packages\websockets\legacy\protocol.py", line 895, in read_data_frame
frame = await self.read_frame(max_size)
File "C:\Users\Alexander\AppData\Local\Programs\Python\Python39\lib\site-packages\websockets\legacy\protocol.py", line 971, in read_frame
frame = await Frame.read(
File "C:\Users\Alexander\AppData\Local\Programs\Python\Python39\lib\site-packages\websockets\legacy\framing.py", line 55, in read
data = await reader(2)
File "C:\Users\Alexander\AppData\Local\Programs\Python\Python39\lib\asyncio\streams.py", line 723, in readexactly
await self._wait_for_data('readexactly')
File "C:\Users\Alexander\AppData\Local\Programs\Python\Python39\lib\asyncio\streams.py", line 517, in _wait_for_data
await self._waiter
File "C:\Users\Alexander\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 280, in _loop_reading
data = fut.result()
File "C:\Users\Alexander\AppData\Local\Programs\Python\Python39\lib\asyncio\windows_events.py", line 812, in _poll
value = callback(transferred, key, ov)
File "C:\Users\Alexander\AppData\Local\Programs\Python\Python39\lib\asyncio\windows_events.py", line 457, in finish_recv
return ov.getresult()
FileNotFoundError: [WinError 53] Не найден сетевой путь
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "E:\Python\Websockets(-).py", line 20, in <module>
loop.run_until_complete(main())
File "C:\Users\Alexander\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 642, in run_until_complete
return future.result()
File "E:\Python\Websockets(-).py", line 11, in main
data = json.loads(await client.recv())['data']
File "C:\Users\Alexander\AppData\Local\Programs\Python\Python39\lib\site-packages\websockets\legacy\protocol.py", line 421, in recv
await self.ensure_open()
File "C:\Users\Alexander\AppData\Local\Programs\Python\Python39\lib\site-packages\websockets\legacy\protocol.py", line 726, in ensure_open
raise self.connection_closed_exc()
websockets.exceptions.ConnectionClosedError: code = 1006 (connection closed abnormally [internal]), no reason
 

regnor

Модератор
Команда форума
Модератор
Июл 7, 2020
2 599
464
83
Решил проблему. Вот код:
Python:
import websockets
import asyncio
import time
import json


  
async def main():
    while True:
        try:
            url = "wss://stream.binance.com:9443/stream?streams=btcrub@miniTicker"
            async with websockets.connect(url) as client:
                while True:
                    data = json.loads(await client.recv())['data']
                    event_time = time.localtime(data['E'] // 1000)
                    event_time = f"{event_time.tm_hour}:{event_time.tm_min}:{event_time.tm_sec}"
                    price = float(data['c'])
                    print(event_time, ' ', price)
                    print('')
        except Exception as ex:
            time.sleep(30)
            continue
if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
так вы перехватываете все ошибки, что не есть хорошо...
в вашем случае была ошибка websockets.exceptions.ConnectionClosedError, вот ее и перехватывайте...
то есть вот так
Python:
...
except websockets.exceptions.ConnectionClosedError as ex:
    ...
 

regnor

Модератор
Команда форума
Модератор
Июл 7, 2020
2 599
464
83
попробовать использовать try/except, перехватывая эту ошибку, и запускать поток заново...
 

Baxudo

Новичок
Пользователь
Июн 6, 2021
14
0
1
попробовать использовать try/except, перехватывая эту ошибку, и запускать поток заново...
Попробовал ваш способ, но наткнулся на следующую проблему - после исправления ошибки программа останавливается, а не возвращается в начало
Python:
import websockets
import asyncio
import time
import json


    
async def main(retry = 10):
    while True:
        try:
            url = "wss://stream.binance.com:9443/stream?streams=btcrub@miniTicker"
            async with websockets.connect(url) as client:
                while True:
                    data = json.loads(await client.recv())['data']
                    event_time = time.localtime(data['E'] // 1000)
                    event_time = f"{event_time.tm_hour}:{event_time.tm_min}:{event_time.tm_sec}"
                    price = float(data['c'])
                    print(event_time, ' ', price)
                    print('')
        except Exception as ex:
            if retry:
                time.sleep(5)
                print(retry, 'Попытки')
                return main(retry=(retry - 1))
        
if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
1.png
 

Baxudo

Новичок
Пользователь
Июн 6, 2021
14
0
1
Попробовал ваш способ, но наткнулся на следующую проблему - после исправления ошибки программа останавливается, а не возвращается в начало
Python:
import websockets
import asyncio
import time
import json


   
async def main(retry = 10):
    while True:
        try:
            url = "wss://stream.binance.com:9443/stream?streams=btcrub@miniTicker"
            async with websockets.connect(url) as client:
                while True:
                    data = json.loads(await client.recv())['data']
                    event_time = time.localtime(data['E'] // 1000)
                    event_time = f"{event_time.tm_hour}:{event_time.tm_min}:{event_time.tm_sec}"
                    price = float(data['c'])
                    print(event_time, ' ', price)
                    print('')
        except Exception as ex:
            if retry:
                time.sleep(5)
                print(retry, 'Попытки')
                return main(retry=(retry - 1))
       
if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
Посмотреть вложение 1280
Решил проблему. Вот код:
Python:
import websockets
import asyncio
import time
import json


    
async def main():
    while True:
        try:
            url = "wss://stream.binance.com:9443/stream?streams=btcrub@miniTicker"
            async with websockets.connect(url) as client:
                while True:
                    data = json.loads(await client.recv())['data']
                    event_time = time.localtime(data['E'] // 1000)
                    event_time = f"{event_time.tm_hour}:{event_time.tm_min}:{event_time.tm_sec}"
                    price = float(data['c'])
                    print(event_time, ' ', price)
                    print('')
        except Exception as ex:
            time.sleep(30)
            continue
if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
 

regnor

Модератор
Команда форума
Модератор
Июл 7, 2020
2 599
464
83
Я пробовал, но он выдавал ошибку, что не знает, что это такое
добавьте import websockets.exceptions
 

Форум IT Специалистов