Skip to content

Commit 0a9dbd8

Browse files
author
Daniel Paquin
authored
Merge pull request danpaquin#337 from uclatommy/patch-2
Fixes websocket dropped connections.
2 parents 4b9e773 + 3923b52 commit 0a9dbd8

File tree

1 file changed

+11
-6
lines changed

1 file changed

+11
-6
lines changed

cbpro/websocket_client.py

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ def _go():
4444
self.stop = False
4545
self.on_open()
4646
self.thread = Thread(target=_go)
47+
self.keepalive = Thread(target=self._keepalive)
4748
self.thread.start()
4849

4950
def _connect(self):
@@ -73,14 +74,15 @@ def _connect(self):
7374

7475
self.ws.send(json.dumps(sub_params))
7576

77+
def _keepalive(self, interval=30):
78+
while self.ws.connected:
79+
self.ws.ping("keepalive")
80+
time.sleep(interval)
81+
7682
def _listen(self):
83+
self.keepalive.start()
7784
while not self.stop:
7885
try:
79-
start_t = 0
80-
if time.time() - start_t >= 30:
81-
# Set a 30 second ping to keep connection alive
82-
self.ws.ping("keepalive")
83-
start_t = time.time()
8486
data = self.ws.recv()
8587
msg = json.loads(data)
8688
except ValueError as e:
@@ -96,11 +98,14 @@ def _disconnect(self):
9698
self.ws.close()
9799
except WebSocketConnectionClosedException as e:
98100
pass
101+
finally:
102+
self.keepalive.join()
99103

100104
self.on_close()
101105

102106
def close(self):
103-
self.stop = True
107+
self.stop = True # will only disconnect after next msg recv
108+
self._disconnect() # force disconnect so threads can join
104109
self.thread.join()
105110

106111
def on_open(self):

0 commit comments

Comments
 (0)