Listening for Reconnect Events
{% tabs %} {% tab title=”Go” %}
{% endtab %}
{% tab title=”Java” %}
server("nats://demo.nats.io:4222").
connectionListener((conn, type) -> {
if (type == Events.RECONNECTED) {
// handle reconnected
} else if (type == Events.DISCONNECTED) {
// handle disconnected, wait for reconnect
}
}).
build();
Connection nc = Nats.connect(options);
// Do something with the connection
nc.close();
{% tab title=”JavaScript” %}
{% endtab %}
{% tab title=”Python” %}
nc = NATS()
async def disconnected_cb():
print("Got disconnected!")
async def reconnected_cb():
# See who we are connected to on reconnect.
await nc.connect(
servers=["nats://demo.nats.io:4222"],
reconnect_time_wait=10,
reconnected_cb=reconnected_cb,
disconnected_cb=disconnected_cb,
)
# Do something with the connection.
{% tab title=”Ruby” %}
{% endtab %}
{% tab title=”C” %}
static void
disconnectedCB(natsConnection *conn, void *closure)
{
// Handle disconnect error event
}
static void
reconnectedCB(natsConnection *conn, void *closure)
{
// Handle reconnect event
}
natsConnection *conn = NULL;
natsOptions *opts = NULL;
natsStatus s = NATS_OK;
s = natsOptions_Create(&opts);
// Connection event handlers are invoked asynchronously
// and the state of the connection may have changed when
// the callback is invoked.
if (s == NATS_OK)
s = natsOptions_SetDisconnectedCB(opts, disconnectedCB, NULL);
if (s == NATS_OK)
s = natsOptions_SetReconnectedCB(opts, reconnectedCB, NULL);
if (s == NATS_OK)
s = natsConnection_Connect(&conn, opts);
(...)
// Destroy objects that were created
natsOptions_Destroy(opts);