Replacing Disconnect Handling
In some cases, an application does not want the AMPS Client
to
reconnect, but instead wants to take a different action if
disconnection occurs. For example, a stateless publisher
that sends ephemeral data (such as telemetry or prices) may want
to exit with an error if the connection is lost rather than
risk falling behind and providing outdated messages. Often,
in this case, a monitoring process will start another publisher
if a publisher fails, and it is better for a message to be
lost than to arrive late.
To cover cases where the application has unusual needs, the AMPS client library allows an application to provide custom disconnect handling.
Your application gets to specify exactly what happens when a
disconnect occurs by supplying a function to
client.setDisconnectHandler()
, which is invoked whenever
a disconnect occurs. This may be helpful for situations
where a particular connection needs to do something completely
different than reconnecting or failing over to another AMPS
server.
Setting the disconnect handler completely replaces the disconnection
failover behavior for a Client
.
The example below shows the basics:
/**
* Call this function to establish a connection to AMPS.
*/
const connectToAMPS = async () => {
try {
await client.connect('ws://localhost:9000/amps/json');
// Successfully connected
}
catch (err) {
// Can't establish connection
}
};
// create a client object
const client = new Client('disconnect-handler-demo');
/*
* disconnectHandler() method is called to supply a function for use
* when AMPS detects a disconnect. At any time, this function may be
* called by AMPS to indicate that the client has disconnected from
* the server, and to allow your application to choose what to do
* about it.
*/
client.disconnectHandler(
/**
* Our disconnect handler’s implementation begins here.
*
* Any custom disconnect handler would be application-specific
* so, for demonstration purposes, we simply log the error.
*
* Notice that this disconnect handler replaces all other
* disconnect handling behavior. When the client is disconnected,
* it will simply log an error to the console. The client
* will not reconnect or take any other action.
*/
(client, error) => {
console.log(error);
}
);
// We begin by connecting and subscribing
connectToAMPS();