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)