Listening for Reconnect Events

    {% tabs %} {% tab title=”Go” %}

    {% endtab %}

    {% tab title=”Java” %}

    1. server("nats://demo.nats.io:4222").
    2. connectionListener((conn, type) -> {
    3. if (type == Events.RECONNECTED) {
    4. // handle reconnected
    5. } else if (type == Events.DISCONNECTED) {
    6. // handle disconnected, wait for reconnect
    7. }
    8. }).
    9. build();
    10. Connection nc = Nats.connect(options);
    11. // Do something with the connection
    12. nc.close();

    {% tab title=”JavaScript” %}

    {% endtab %}

    {% tab title=”Python” %}

    1. nc = NATS()
    2. async def disconnected_cb():
    3. print("Got disconnected!")
    4. async def reconnected_cb():
    5. # See who we are connected to on reconnect.
    6. await nc.connect(
    7. servers=["nats://demo.nats.io:4222"],
    8. reconnect_time_wait=10,
    9. reconnected_cb=reconnected_cb,
    10. disconnected_cb=disconnected_cb,
    11. )
    12. # Do something with the connection.

    {% tab title=”Ruby” %}

    {% endtab %}

    {% tab title=”C” %}

    1. static void
    2. disconnectedCB(natsConnection *conn, void *closure)
    3. {
    4. // Handle disconnect error event
    5. }
    6. static void
    7. reconnectedCB(natsConnection *conn, void *closure)
    8. {
    9. // Handle reconnect event
    10. }
    11. natsConnection *conn = NULL;
    12. natsOptions *opts = NULL;
    13. natsStatus s = NATS_OK;
    14. s = natsOptions_Create(&opts);
    15. // Connection event handlers are invoked asynchronously
    16. // and the state of the connection may have changed when
    17. // the callback is invoked.
    18. if (s == NATS_OK)
    19. s = natsOptions_SetDisconnectedCB(opts, disconnectedCB, NULL);
    20. if (s == NATS_OK)
    21. s = natsOptions_SetReconnectedCB(opts, reconnectedCB, NULL);
    22. if (s == NATS_OK)
    23. s = natsConnection_Connect(&conn, opts);
    24. (...)
    25. // Destroy objects that were created
    26. natsOptions_Destroy(opts);