From 056982665cf15d78b238effabfc5c3fbc0f04492 Mon Sep 17 00:00:00 2001 From: "Mohamed I. Hammad" Date: Sun, 25 Aug 2019 13:40:04 -0700 Subject: [PATCH] Set stop=true if an error occurs while creating a connection When an exception is thrown during opening a connection or subscribing, self.stop still remains false. Users of WebsocketClient class will have no way to know whether a connection is live and functioning. This commit allows users to rely on self.stop to figure this out. --- cbpro/websocket_client.py | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/cbpro/websocket_client.py b/cbpro/websocket_client.py index f1b0f97..b6fc95d 100644 --- a/cbpro/websocket_client.py +++ b/cbpro/websocket_client.py @@ -43,8 +43,8 @@ def _go(): self.stop = False self.on_open() - self.thread = Thread(target=_go) - self.keepalive = Thread(target=self._keepalive) + self.thread = Thread(target=_go, name='socket-worker-thread') + self.keepalive = Thread(target=self._keepalive, name='keepalive-thread') self.thread.start() def _connect(self): @@ -70,12 +70,14 @@ def _connect(self): sub_params['passphrase'] = auth_headers['CB-ACCESS-PASSPHRASE'] sub_params['timestamp'] = auth_headers['CB-ACCESS-TIMESTAMP'] - self.ws = create_connection(self.url) - - self.ws.send(json.dumps(sub_params)) + try: + self.ws = create_connection(self.url) + self.ws.send(json.dumps(sub_params)) + except Exception as e: + self.on_error(e) def _keepalive(self, interval=30): - while self.ws.connected: + while self.ws and self.ws.connected: self.ws.ping("keepalive") time.sleep(interval) @@ -99,7 +101,8 @@ def _disconnect(self): except WebSocketConnectionClosedException as e: pass finally: - self.keepalive.join() + if self.keepalive.is_alive(): + self.keepalive.join() self.on_close()