简体   繁体   English

Python WebSocket 客户端堆栈溢出重新连接

[英]Python WebSocket Client Stack Overflow Reconnecting

I created a class for a WebSocket client that reopen when disconnecting unintentionely.我为 WebSocket 客户端创建了一个 class,该客户端在意外断开连接时重新打开。 After several disconnection, I have a Python stack overflow.几次断开后,我有一个 Python 堆栈溢出。

  • 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:这是我的 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}')

May be because the old thread is not really closed and then related memory is not released...可能是因为旧线程没有真正关闭,然后相关的 memory 没有发布...

An useful link on a Github thread may be this this one: Github 线程上的一个有用链接可能是这个:

LINK TO DISCUSSION ON GITHUB GITHUB 讨论链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM