Connections
When you instantiate a client, a realtime connection is established and maintained with Ably. You can interact with the connection using the ChatClient.connection
object in order to monitor a client's connection status.
Connection statuses
A connection can have any of the following statuses:
Status | Description |
---|---|
initialized | A connection object has been initialized but not yet connected. |
connecting | A connection attempt has been initiated, this status is entered as soon as the SDK has completed initialization, and is re-entered each time connection is re-attempted following disconnection. |
connected | A connection exists and is active. |
disconnected | A temporary failure condition when no current connection exists. The disconnected status is entered if an established connection is dropped, or if a connection attempt is unsuccessful. |
suspended | A long term failure condition when no current connection exists because there is no network connectivity or available host. The suspended status is entered after a failed connection attempt if there has then been no connection for a period of two minutes. In the suspended status, an SDK will periodically attempt to open a new connection every 30 seconds. Rooms will be reattached on a successful reconnection, however message history will not be automatically recovered. |
failed | This status is entered if the SDK encounters a failure condition that it cannot recover from. This may be a fatal connection error received from the Ably service, such as an attempt to connect with an incorrect API key, or some local terminal error, such as that the token in use has expired and the SDK does not have any way to renew it. |
Use the status
property to check which status a connection is currently in:
Use the connection.onStatusChange()
method to register a listener for status change updates:
Use the off()
function returned in the onStatusChange()
response to remove a listener:
Use the connection.offAllStatusChange()
method to remove all connection status listeners:
Handle connection discontinuity
If a client briefly loses connection to Ably, for example when driving through a tunnel, the SDK will attempt to recover the connection. If the disruption lasts for less than 2 minutes, then on reconnection the SDK will automatically reattach to any rooms and replay any missed messages.
During periods of discontinuity greater than 2 minutes then you will need to take steps to recover any missed messages, such as by calling history.
The Chat SDK provides an onDiscontinuity()
handler exposed via the Room object to assist with this. This method enables you to register a listener that will be notified when discontinuity occurs in the room so that you can handle it, as needed.
For example, for messages:
Use the off()
function returned in the onDiscontinuity()
response to remove a listener:
The discontinuity handler is accessible via the Room object.