예제 #1
0
async def main():
    # Create a client and subscribe to topics
    client = PubSubClient(["guns", "germs"], callback=on_events)

    async def on_steel(data, topic):
        print("running callback steel!")
        print("Got data", data)
        asyncio.create_task(client.disconnect())

    client.subscribe("steel", on_steel)
    client.start_client(f"ws://localhost:{PORT}/pubsub")
    await client.wait_until_done()
async def test_disconnect_callback_without_context(delayed_death_server):
    """
    Test reconnecting when a server hangups AFTER connect and that the disconnect callback work
    """
    # finish trigger
    finish = asyncio.Event()
    disconnected = asyncio.Event()

    async def on_disconnect(channel):
        disconnected.set()

    async def on_connect(client, channel):
        try:
            print("Connected")
            # publish events (with sync=False to avoid deadlocks waiting on the publish to ourselves)
            published = await client.publish([EVENT_TOPIC],
                                             data=DATA,
                                             sync=False,
                                             notifier_id=gen_uid())
            assert published.result == True
        except RpcChannelClosedException:
            # expected
            pass

    # Create a client and subscribe to topics
    client = PubSubClient(on_disconnect=[on_disconnect],
                          on_connect=[on_connect])

    async def on_event(data, topic):
        assert data == DATA
        finish.set()

    # subscribe for the event
    client.subscribe(EVENT_TOPIC, on_event)
    # start listentining
    client.start_client(uri)
    # wait for the client to be ready to receive events
    await client.wait_until_ready()
    # publish events (with sync=False toa void deadlocks waiting on the publish to ourselves)
    published = await client.publish([EVENT_TOPIC],
                                     data=DATA,
                                     sync=False,
                                     notifier_id=gen_uid())
    assert published.result == True
    # wait for finish trigger
    await asyncio.wait_for(finish.wait(), 5)
    await client.disconnect()
    await asyncio.wait_for(disconnected.wait(), 1)
    assert disconnected.is_set()