Replacing Disconnect Handling

In some cases, an application does not want the AMPS client to reconnect, but instead wants to take 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 implement failover behavior itself by completely replacing the default behavior.

Setting the disconnect handler completely replaces the disconnection and failover behavior for an HAClient and provides the only disconnection and failover behavior for a Client.

The handler runs on the thread that detects the disconnect. This may be the client receive thread (for example, if the disconnect is detected due to heartbeating) or an application thread (for example, if the disconnect is detected when sending a command to AMPS).

The example below shows the basics:

public class MyApp
{
    string _uri;
    public MyApp(string uri)
    {
        _uri = uri;
        Client client = new Client("sampleClient");

        // setDisconnectHandler() 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.setDisconnectHandler(ExitOnDisconnection);
        client.connect(uri);
        client.logon();
        client.subscribe((m) => ShowMessage(m), "orders", 5000) ;
    }

    public void ShowMessage(Message m)
    {
        // display order data to the user
        ...
    }


    // Our disconnect handler's implementation begins here.
    //
    // If we wanted the application to reconnect, resubmit the
    // subscription, and so on, we would use the HAClient (and
    // the provided disconnect handler).
    //
    // In this case, we want to exit with an error if the connection
    // ever fails, so we replace the disconnect handler with a function
    // that does exactly that.

    public void ExitOnDisconnection(Client client)
    {
       Environment.Exit(1); // Or equivalent, depending on environment
    }
}

Last updated