I created a class for a WebSocket client that reopen when disconnecting unintentionely. After several disconnection, I have a Python stack overflow.
- Why do I have this issue ? I think it comes from the infinite loop trying to reconnect, but this is the behaviour intended
- Is there a way to avoid this issue ? if yes, how ? If no, why ?
Any comments will be much appreciated. I hope this will help others
Here is my class:
import websocket
import json
class MyWebSocketClient(object):
def __init__(self, url):
self.url = url
self.connected = False
self.running = False
def start(self):
self.running = True
self.ws = websocket.WebSocketApp(
url=self.URL,
on_open=self.on_open,
on_message=self.on_message,
on_close=self.on_close,
on_error=self.on_error,
)
self.ws.run_forever()
def stop(self):
self.running = False
self.ws.keep_running = False
def send(self, data: dict):
data = json.dumps(data, separators=(",", ":"), indent=None)
self.ws.send(data)
def on_open(self):
logger.info('Connexion opened')
self.connected = True
def on_message(self, data):
logger.info(f'Data received: {data}')
def on_close(self):
logger.info(f'Connection closed')
self.connected = False
if self.running:
self.start()
def on_error(self, err):
logger.error(f'Error: {err}')