From d3be010ffde3f3f2fe1141c7dbf9a8056b0fd666 Mon Sep 17 00:00:00 2001 From: Tony Garnock-Jones Date: Wed, 21 Nov 2018 13:22:00 +0000 Subject: [PATCH] on_connected callback --- chat.py | 2 +- syndicate/mini/core.py | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/chat.py b/chat.py index 0f7a48d..78ce251 100644 --- a/chat.py +++ b/chat.py @@ -38,7 +38,7 @@ S.Endpoint(conn, S.Observe(Says(S.CAPTURE, S.CAPTURE)), async def reconnect(loop): while True: - await conn.main(loop) + await conn.main(loop, on_connected=lambda: print('-'*50, 'Connected')) if not conn: break print('-'*50, 'Disconnected') await asyncio.sleep(2) diff --git a/syndicate/mini/core.py b/syndicate/mini/core.py index fad8e4a..d275b29 100644 --- a/syndicate/mini/core.py +++ b/syndicate/mini/core.py @@ -157,7 +157,7 @@ class TcpConnection(Connection, asyncio.Protocol): if self.stop_signal: self.stop_signal.set_result(True) - async def main(self, loop): + async def main(self, loop, on_connected=None): if self.transport is not None: raise Exception('Cannot run connection twice!') @@ -173,6 +173,7 @@ class TcpConnection(Connection, asyncio.Protocol): return False try: + if on_connected: on_connected() await self.stop_signal return True finally: @@ -196,7 +197,7 @@ class WebsocketConnection(Connection): if self.ws: self.loop.call_soon_threadsafe(lambda: self.loop.create_task(self.ws.close())) - async def main(self, loop): + async def main(self, loop, on_connected=None): if self.ws is not None: raise Exception('Cannot run connection twice!') @@ -204,6 +205,7 @@ class WebsocketConnection(Connection): try: async with websockets.connect(self.url) as ws: + if on_connected: on_connected() self.ws = ws self._on_connected() try: