Skip to content

Commit 230256e

Browse files
committed
improve async websocket examples
1 parent 1464e9e commit 230256e

File tree

1 file changed

+18
-12
lines changed

1 file changed

+18
-12
lines changed

xrpl/asyncio/clients/async_websocket_client.py

Lines changed: 18 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,7 @@
1919
class AsyncWebsocketClient(AsyncClient, WebsocketBase):
2020
"""
2121
An async client for interacting with the rippled WebSocket API.
22-
23-
Instead of calling ``open`` and ``close`` yourself, you
22+
Instead of calling ``open`` and ``close`` yourself, you
2423
can use a context like so::
2524
2625
async with AsyncWebsocketClient(url) as client:
@@ -137,7 +136,7 @@ async def main():
137136
streams=[StreamParameter.LEDGER],
138137
))
139138
print("Unsubscribed from the ledger!")
140-
except:
139+
except Exception:
141140
# if you wish you perform some logic when the websocket
142141
# connection closes due to error, you can catch and run
143142
# whatever you need to here. this is equivalent to the
@@ -176,7 +175,11 @@ async def websocket_supervisor():
176175
while True:
177176
try:
178177
await long_websocket_task()
179-
except:
178+
except KeyboardInterrupt:
179+
# allow crtl-c to actually cancel
180+
raise
181+
except Exception:
182+
# anything else reconnects
180183
print("Lost connection! Reconnecting")
181184
182185
@@ -190,15 +193,18 @@ async def long_websocket_task():
190193
# set up a listener task
191194
listener = asyncio.create_task(on_message(client))
192195
193-
# subscribe to the ledger
194-
await client.send(Subscribe(
195-
streams=[StreamParameter.LEDGER],
196-
))
196+
try:
197+
# subscribe to the ledger
198+
await client.send(Subscribe(
199+
streams=[StreamParameter.LEDGER],
200+
))
197201
198-
# sleep infinitely until the connection closes on us
199-
while client.is_open():
200-
await asyncio.sleep(0)
201-
listener.cancel()
202+
# sleep infinitely until the connection closes on us
203+
while client.is_open():
204+
await asyncio.sleep(0)
205+
finally:
206+
# whether or not there is an error, cancel the listener
207+
listener.cancel()
202208
203209
204210
async def main():

0 commit comments

Comments
 (0)