Python WebSocketApp 报错提示缺少 on_closed 函数参数如何解决?

新手上路,请多包涵

python使用 websocket模块,初始化websocket连接时报错 ClientThread.on_closed() missing 2 required positional arguments: 'close_status_code' and 'close_msg'

def init_connection(url):
    """
    ws = websocket.WebSocketApp(url, on_open=ClientThread.on_open, on_message=ClientThread.on_message,
                                on_close=ClientThread.on_closed, on_error=ClientThread.on_error)
    """

    ws = websocket.WebSocketApp(url, on_open=ClientThread.on_open, on_message=ClientThread.on_message,
                                on_close=ClientThread.on_closed, on_error=ClientThread.on_error)

ClientThread 类定义

class ClientThread(threading.Thread):
    def __init__(self, ws):
        threading.Thread.__init__(self)
        self.ws = ws
        ws.is_connect = False

    def run(self):
        self.ws.run_forever()

    def return_is_connect(self):
        return self.ws.is_connect

    def on_message(ws, message):
        print("received message: " + message)
        # 该判断方式仅用作demo展示, 生产环境请使用json解析
        if "\"errorCode\":\"0\"" not in message:
            sys.exit()

    def on_open(ws):
        print("connection open")
        ws.is_connect = True

    def on_closed(ws, close_status_code, close_msg):
        if not close_status_code:
            close_status_code = 'None'
        if not close_msg:
            close_msg = 'None'
        print("connection closed, code: " + close_status_code + ", reason: " + close_msg)

    def on_error(ws, error):
        print(error)

修改了类中函数定义

    def on_closed(ws, close_status_code, close_msg):
        if not close_status_code:
            close_status_code = 'None'
        if not close_msg:
            close_msg = 'None'
        print("connection closed, code: " + close_status_code + ", reason: " + close_msg)
阅读 736
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏