Connection
The Ably Realtime library establishes and maintains a connection to the Ably service, using the most efficient transport available, typically WebSockets. The Ably realtime protocol operates and multiplexes all channel traffic over that connection.
Getting started
The Ably Realtime library will open and maintain a connection to the Ably realtime servers as soon as it is instanced. The Connection
object provides a straightforward API to monitor and manage connection state.
The following example relies on the default auto-connect behavior of the library, and then subscribes to the connection’s connected
event.
var ably = new Ably.Realtime('xVLyHw.RwgZLw:duns-Qz1ws1Qr8U9');
ably.connection.on('connected', function() {
alert('Connected, that was easy');
})
var Ably = require('ably');
var ably = new Ably.Realtime('xVLyHw.RwgZLw:duns-Qz1ws1Qr8U9');
ably.connection.on('connected', function() {
console.log('Connected, that was easy');
})
ably = Ably::Realtime.new('xVLyHw.RwgZLw:duns-Qz1ws1Qr8U9')
ably.connection.on(:connected) do
puts "Connected, that was easy"
end
AblyRealtime ably = new AblyRealtime("xVLyHw.RwgZLw:duns-Qz1ws1Qr8U9");
ably.connection.on('connected', new ConnectionStateListener() {
@Override
public void onConnectionStateChanged(ConnectionStateChange change) {
System.out.println("Connected, that was easy");
}
});
AblyRealtime ably = new AblyRealtime("xVLyHw.RwgZLw:duns-Qz1ws1Qr8U9");
ably.Connection.On(ConnectionState.Connected, args => {
Console.WriteLine("Connected, that was easy");
});
ARTRealtime *ably = [[ARTRealtime alloc] initWithKey:@"xVLyHw.RwgZLw:duns-Qz1ws1Qr8U9"];
[ably.connection on:ARTRealtimeConnectionEventConnected callback:^(ARTConnectionStateChange *change) {
NSLog(@"Connected, that was easy");
}];
let realtime = ARTRealtime(key: "xVLyHw.RwgZLw:duns-Qz1ws1Qr8U9")
realtime.connection.on(.connected) { change in
print("Connected, that was easy")
}
final realtime = ably.Realtime(key: 'xVLyHw.RwgZLw:duns-Qz1ws1Qr8U9');
final channel = realtime
.on(ably.ConnectionStateChange.connected)
.subscribe((ably.ConnectionStateChange stateChange) {
print('Connected, that was easy');
}
);
Note that all examples on this page assume you are running them within an EventMachine reactor. Find out more in our Realtime usage documentation.
Connection state explained
Although connection state is temporary, the Ably protocol provides continuity of message delivery between the client and the service, provided that a dropped connection is reestablished by the client within a limited interval (typically around 2 minutes). Beyond that, the connection becomes stale and the system will not attempt to recover the connection state. The lifecycle of a connection, and the strategy for reconnecting on failure, reflect the transient nature of the connection state.
The client library is responsible for managing the connection; this includes selecting a transport (in those environments supporting multiple transports), selecting a host to connect to (automatically falling back to an alternate datacenter host if the closest datacenter is unreachable), and managing continuity of operation when the connection drops.
When the library is instanced, if connectivity to the service is available, the library will establish a connection immediately, and if the connection drops at any time it will attempt to re-establish it by making repeated connection attempts every 15 seconds for up to two minutes.
If, after that time, there has been no connection, the library falls back to a lower level of activity, still periodically attempting reconnection at 30 second intervals. This reflects the assumption that there will no longer be recoverable connection state and the client may be offline for a period of time. As soon as a reconnection attempt has been successful, the system reverts to the more active connection behavior. Further, you can explicitly trigger a reconnection attempt at any time if you wish to implement a different reconnection strategy.
The connection object provides methods to observe the lifecycle of the connection and to trigger state transitions.
Available connection states
A series of connection states is defined as follows:
- initialized
- A
Connection
object having this state has been initialized but no connection has yet been attempted.
- connecting
- A connection attempt has been initiated. The connecting state is entered as soon as the library has completed initialization, and is reentered each time connection is re-attempted following disconnection.
- connected
- A connection exists and is active.
- disconnected
- A temporary failure condition. No current connection exists because there is no network connectivity or no host is available.
The disconnected state is entered if an established connection is dropped, or if a connection attempt was unsuccessful. In the disconnected state the library will periodically attempt to open a new connection (approximately every 15 seconds), anticipating that the connection will be re-established soon and thus connection and channel continuity will be possible.
In this state, developers can continue to publish messages as they are automatically placed in a local queue, to be sent as soon as a connection is reestablished. Messages published by other clients whilst this client is disconnected will be delivered to it upon reconnection, so long as the connection was resumed within 2 minutes.
After 2 minutes have elapsed, recovery is no longer possible and the connection will move to thesuspended
state.
- suspended
- A long term failure condition. No current connection exists because there is no network connectivity or no host is available.
The suspended state is entered after a failed connection attempt if there has then been no connection for a period of two minutes. In the suspended state, the library will periodically attempt to open a new connection every 30 seconds. Developers are unable to publish messages in this state. A new connection attempt can also be triggered by an explicit call toconnect()
connect
Connect()
:#connect on theConnection
object.
Once the connection has been re-established, channels will be automatically re-attached. The client has been disconnected for too long for them to resume from where they left off, so if it wants to catch up on messages published by other clients while it was disconnected, it needs to use the history API.
- closing
- An explicit request by the developer to close the connection has been sent to the Ably service. If a reply is not received from Ably within a short period of time, the connection will be forcibly terminated and the connection state will become
closed
.
- closed
- The connection has been explicitly closed by the client.
In the closed state, no reconnection attempts are made automatically by the library, and clients may not publish messages. No connection state is preserved by the service or by the library. A new connection attempt can be triggered by an explicit call toconnect()
connect
Connect()
:#connect on theConnection
object, which will result in a new connection.
- failed
- This state is entered if the client library encounters a failure condition that it cannot recover from. This may be a fatal connection error received from the Ably service (e.g. an attempt to connect with an incorrect API key), or some local terminal error (e.g. the token in use has expired and the library does not have any way to renew it).
In the failed state, no reconnection attempts are made automatically by the library, and clients may not publish messages. A new connection attempt can be triggered by an explicit call toconnect()
connect
Connect()
:#connect on theConnection
object.
Typical connection state sequences
The library is initialized and initiates a successful connection.
initialized → connecting → connected
An existing connection is dropped and reestablished on the first attempt.
connected → disconnected → connecting → connected
An existing connection is dropped, and reestablished after several attempts but within a two minute interval.
connected → disconnected → connecting → disconnected → … → connecting → connected
There is no connection established after initializing the library.
initialized → connecting → disconnected → connecting → … → suspended
After a period of being offline a connection is reestablished.
suspended → connecting → suspended → … → connecting → connected
Listening for state changes
The Connection
object is an EventEmitter
and emits an event whose name is the new state whenever there is a connection state change. An event listener function is passed a ConnectionStateChange object as the first argument for state change events.An event listener function is passed a ConnectionStateChange object as the first argument for state change events.The event block is passed the new state and an optional ErrorInfo
object
The Connection
object can also emit an event that is not a state change: an update
event. This happens when there’s a change to connection conditions for which the connection state doesn’t change – that is, when the library remains connected, e.g. after a reauth.
realtime.connection.on('connected', function(stateChange) {
console.log('Ably is connected');
});
realtime.connection.on('connected', function(stateChange) {
console.log('Ably is connected');
});
Alternatively a listener may be registered so that it receives all state change events.
realtime.connection.on(function(stateChange) {
console.log('New connection state is ' + stateChange.current);
});
realtime.connection.on(function(stateChange) {
console.log('New connection state is ' + stateChange.current);
});
Previously registered listeners can be removed individually or all together.
/* remove a listener registered for a single event */
realtime.connection.off('connected', myListener);
/* remove a listener registered for all events */
realtime.connection.off(myListener);
/* remove all event listeners */
realtime.connection.off();
/* remove a listener registered for a single event */
realtime.connection.off('connected', myListener);
/* remove a listener registered for all events */
realtime.connection.off(myListener);
/* remove all event listeners */
realtime.connection.off();
realtime.connection.on(ConnectionEvent.connected, new ConnectionStateListener() {
@Override
public void onConnectionStateChanged(ConnectionStateChange change) {
System.out.println("New state is connected");
}
});
Alternatively a listener may be registered so that it receives all state change events.
realtime.connection.on(new ConnectionStateListener() {
@Override
public void onConnectionStateChanged(ConnectionStateChange change) {
System.out.println("New state is " + change.current.name());
}
});
Previously registered listeners can be removed individually or all together.
/* remove a single listener */
realtime.connection.off(myListener);
/* remove all event listeners */
realtime.connection.off();
realtime.Connection.On(ConnectionState.Connected, args => {
Console.WriteLine("Connected, that was easy")
});
Alternatively a handler may be registered so that it receives all state change events.
realtime.Connection.On(args => {
Console.WriteLine("New state is " + args.Current)
});
Previously registered handlers can be removed individually or all together.
/* remove a single handler */
realtime.Connection.Off(action);
/* remove all event handlers */
realtime.Connection.Off();
realtime.connection.on(:connected) do
puts 'Ably is connected'
end
Alternatively a listener may be registered so that it receives all state change events.
realtime.connection.on do |state_change|
puts "New connection state is #{state_change.current}"
end
Previously registered listeners can be removed individually or all together.
# remove a listener registered for a single even
realtime.connection.off :connected, &block
# remove a listener registered for all events
realtime.connection.off &block
# remove all event listeners
realtime.connection.off
ARTEventListener *listener = [realtime.connection on:ARTRealtimeConnectionEventConnected callback:^(ARTConnectionStateChange *change) {
NSLog(@"Ably is connected");
}];
Alternatively a listener may be registered so that it receives all state change events.
ARTEventListener *listener = [realtime.connection on:^(ARTConnectionStateChange *change) {
NSLog(@"New connection state is %lu", (unsigned long)change.current);
}];
Previously registered listeners can be removed individually or all together.
// remove a listener registered for a single event
[realtime.connection off:ARTRealtimeConnectionEventConnected listener:listener];
// remove a listener registered for all events
[realtime.connection off:listener];
// remove all event listeners
[realtime.connection off];
let listener = realtime.connection.on(.connected) { change in
print("Ably is connected")
}
Alternatively a listener may be registered so that it receives all state change events.
let listener = realtime.connection.on { change in
print("New connection state is \(change!.current)")
}
Previously registered listeners can be removed individually or all together.
// remove a listener registered for a single event
realtime.connection.off(.connected, listener: listener)
// remove a listener registered for all events
realtime.connection.off(listener)
// remove all event listeners
realtime.connection.off()
Handling failures
The client libraries will attempt to automatically recover from non-fatal error conditions. However, it will emit events to say what it’s doing, so you can handle them yourself if you prefer.
Fatal errors
Some classes of errors are fatal. These cause the connection to move to the FAILED
state. The client library will not attempt any automatic recovery actions. For example, if your token expires and the client library has no way to get a new token (so no authUrl and authCallback), the connection will enter the FAILED
state
While the library will not automatically attempt to reconnect in the FAILED
state, explicit calls to connect()
will make the client try again.
Nonfatal errors
Other classes of error are nonfatal. For example, a client may have network connectivity issues. The library will attempt to automatically reconnect and recover from these sort of issues, as detailed in the DISCONNECTED
and SUSPENDED
explanations in the Available connection states section.
If message continuity is lost in the process, e.g. because you have been disconnected from Ably for more than two minutes, the library will notify you though the resumed
-flag mechanism, detailed in the Channels and Messages page.
Connection state recovery
The Ably system preserves connection state to allow connections to continue transparently across brief disconnections. The connection state that is tracked includes the messages sent to the client on the connection, members present on a channel and the set of channels that the client is attached to.
There are two modes of connection state recovery:
-
resume
: this is transparent recovery of a live client instance across disconnections. Upon disconnection, the library will automatically re-attempt connection and, once the connection is re-established, any missed messages will be sent to the client. The developer does not need to do anything to trigger this behavior; all client channel event listeners remain attached and are called when the backlog of messages is received.
-
recover
: this addresses the case in which a new client library instance wishes to connect and recover the state of an earlier connection. This occurs typically in a browser environment when the page has been refreshed and therefore the client instance is disposed and no client state is retained. In this case any message listeners associated with channels will no longer exist so it is not possible for the library simply to send the message backlog on reconnection; instead the client must re-subscribe to each channel it is interested in within 15 seconds, and its message listener(s) will be called with any message backlog for that channel. If it had any members in the presence set, they will need to explicitly re-enter. If the previously attached channels are not re-attached within 15 seconds of a connection being recovered, the client will lose the ability to continue the message stream from before; any subsequent attach() will result in a fresh attachment, with no backlog sent. A client requests recovery of connection state by including a recovery string in the client options when instancing the Realtime library. See connection state recover options for more info.
In either case, when a connection is resumed or recovered, the message backlog held on the server will be pushed to the client. However, any new messages published will be sent as they become available or messages could be indefinitely deferred on very heavily loaded connections. Therefore the system does not guarantee that messages received after reconnection are delivered in the same order that would have occurred if the connection had not been dropped. In the recover
case, in particular, the order of the message delivery depends on the timing of the re-attachment of each channel.
Connection state recover options
In recover
mode it is necessary to request recovery mode in the client options when instancing the library. Recovery requires that the library knows the previous connection’s recoveryKey
recovery_key
RecoveryKey
value (which includes both the private unique Connection#key
Connection#Key
and the last message serial received on that connection). As the recovery key is never shared with any other clients, it allows Ably to safely resend message backlogs to the original client.
In the browser environment, if a callback is provided in the recover
option, when the window.beforeunload
event fires, the connection details, including the recoveryKey
, are stored in the browser’s sessionStorage. The provided recover
callback is then invoked whenever the connection state can be recovered and just before a connection is established, passing in the LastConnectionDetails
. The callback is then responsible for confirming whether the connection state should be recovered or not. For example, it is common to recover connection state when the page is reloaded but not for different pages the user has navigated to. The callback allows the developer to decide if the connection should be recovered or not at the time the new connection is established by inspecting the LastConnectionDetails
and evaluating that against any other application state. Below are two examples:
- Always recover – always recover the previous connection state if possible
var ably = new Ably.Realtime({
authUrl: '/obtainToken',
recover: function(_, cb) { cb(true); }
});
var ably = new Ably.Realtime({
authUrl: '/obtainToken',
recover: function(_, cb) { cb(true); }
});
- Sometimes recover – recover the previous connection state conditionally based on some logic
var ably = new Ably.Realtime({
authUrl: '/obtainToken',
recover: function(lastConnectionDetails, cb) {
/* Only recover if the current path hasn't changed, start a
* fresh connection if it has. This is just an example, you
* can use whatever logic your app requires */
if (lastConnectionDetails.location.href === document.location.href) {
cb(true); /* recover connection */
} else {
cb(false); /* do not recover connection */
}
}
});
var ably = new Ably.Realtime({
authUrl: '/obtainToken',
recover: function(lastConnectionDetails, cb) {
/* Only recover if the current path hasn't changed, start a
* fresh connection if it has. This is just an example, you
* can use whatever logic your app requires */
if (lastConnectionDetails.location.href === document.location.href) {
cb(true); /* recover connection */
} else {
cb(false); /* do not recover connection */
}
}
});
Please note that as sessionStorage
is used to persist the LastConnectionDetails
between page reloads, it is only available for pages in the same origin and top-level browsing context.
Alternatively, if it is necessary to be explicit about the connection recoveryKey
, the connection can be recovered by providing the last value of the connection’s recoveryKey
value in the client options recover
attribute when instancing the library.
Connection recovery constraints
Connection recovery requires that the new client library instance uses credentials that are compatible with those used for the inherited connection; this requires that the same authentication mode is used, with the same key. If token auth was used, the same token is not required, but the token used must have the same capability
and clientId
client_id
ClientId
. This ensures that the client recovering the connection cannot receive a backlog of messages that its new credentials are not entitled to access. Incompatible credentials will result in an unrecoverable connection error.
Connection API reference
- Properties
Connection PropertiesARTConnection PropertiesAbly::Realtime::Connection Attributesio.ably.lib.realtime.Connection MembersIO.Ably.Realtime.Connection Properties
The Connection
object exposes the following public propertiesattributesmembers:
idId
A unique public identifier String
for this connection, used to identify this member in presence events and messages.
stateState
The current io.ably.lib.realtime.ConnectionState
state
IO.Ably.Realtime.ConnectionState
state
Ably::Realtime::Connection::STATE
state
ARTRealtimeConnectionState
state
state String
of this Connection. See the Connection
states for more information.
errorReasonreasonErrorReasonerror_reason
When a connection failure occurs this attributememberproperty contains the ErrorInfo
AblyException
.
keyKey
A unique private connection key String
used to recover or resume a connection, assigned by Ably. When recovering a connection explicitly, the recoveryKey
recovery_key
is used in the recover
client options as it contains both the key
and the last message serial
.
This private connection key can also be used by other REST clients to publish on behalf of this client. See the publishing over REST on behalf of a realtime client documentation for more info.
recoveryKeyrecovery_keyRecoveryKey
The recovery key String
can be used by another client to recover this connection’s state in the recover
Recover
client options propertymemberattribute. See connection state recover options for more information.
serialSerial
The serial number Integer
of the last message to be received on this connection, used automatically by the library when recovering or resuming a connection. When recovering a connection explicitly, the recoveryKey
recovery_key
RecoveryKey
is used in the recover
Recover
client options as it contains both the key
and the last message serial
.
Connection MethodsARTConnection MethodsAbly::Realtime::Connection Methodsio.ably.lib.realtime.Connection MethodsIO.Ably.Realtime.Connection Methods
connectConnect
connect()Deferrable connect → yields
Connection
void connect()void Connect()Futureconnect()
Explicitly calling connect
Connect
is unnecessary unless the ClientOptions
attribute autoConnect
auto_connect
AutoConnect
is false
. Unless already connected
or connecting
, this method causes the connection to open, entering the connecting
state.
Returns
A Deferrable
object is returned from this method.
On successfully connecting to Ably, the registered success blocks for the Deferrable
and any block provided to this method yields a Connection
object.
Failure to connect will trigger the errback callbacks of the Deferrable
with an ErrorInfo
object containing an error response as defined in the Ably REST API documentation.
Returns
Future<void>
Failure to connect will throw an AblyException
with an errorInfo
property containing an error response as defined in the Ably REST API documentation.
closeClose
close()Deferrable close → yields
Connection
void close()void Close()Futureclose()
Causes the connection to close, entering the closing
state. Once closed
, the library will not attempt to re-establish the connection without an explicit call to connect()
Connect()
connect
.
Returns
A Deferrable
object is returned from this method.
On successfully closing the connection, the registered success blocks for the Deferrable
and any block provided to this method yields a Connection
object.
Failure to close the connection will trigger the errback callbacks of the Deferrable
with an ErrorInfo
object containing an error response as defined in the Ably REST API documentation.
onOn
There are threetwo overloaded versions of this method:
on(String event, listener(ConnectionStateChange stateChange))on(ConnectionEvent *event) → yields ConnectionStateChangevoid on(ConnectionEvent event, ConnectionStateListener listener)on(event: ARTRealtimeConnectionEvent, call: (ARTConnectionStateChange?) → Void) → ARTEventListenervoid On(ConnectionEvent event, Action<ConnectionStateChange> action)Stream<ably.ConnectionStateChange> on(ably.ConnectionStateChange stateChange)
The Stream returned can be subscribed for with a listener.
final streamSubscription = stream.listen(listener)
Register the given listener blockfunctionaction for the specified ConnectionEvent
on the Connection
. The listener is passed a ConnectionStateChange object that contains the current state, previous state, and an optional reason for the event or state change.
on(String[] events, listener(ConnectionStateChange stateChange))
Same as above, but registers multiple listeners, one for each event in the array.
on(listener(ConnectionStateChange stateChange))on → yields ConnectionStateChangevoid on(ConnectionStateListener listener)on(call: (ARTConnectionStateChange?) → Void) → ARTEventListenervoid On(Action<ConnectionStateChange> action)Stream<ably.ConnectionStateChange> on()
The Stream returned can be subscribed for with a listener.
final streamSubscription = stream.listen(listener)
Register the given listener blockfunctionaction for all ConnectionEvents on the Connection
. The listener is passed a ConnectionStateChange object that contains the current state, previous state, the event, and an optional reason for the event or state change. (For the update
event, the current and previous states will be the same).
If an exception is thrown in the listener and bubbles up to the event emitter, it will be caught and logged at error
level, so as not to affect other listeners for the same event
Parameters
- event(s)
- the connection event(s) to subscribe to
Type:String
orString[]
- event
- the connection event to subscribe to
Type:ConnectionEvent
- event
- the connection event to subscribe to
Type:ConnectionEvent
- event
- the connection event as a Symbol such as
:connected
orConnectionEvent
object to subscribe to
Type:ConnectionEvent
- event
- the connection event to subscribe to
Type:ARTRealtimeConnectionEvent
- event
- the connection event to subscribe to
Type:ConnectionEvent
- listener
- is a function of the form
function(stateChange)
to be notified for matching events - listener
- listener to be notified for matching events
Type:ConnectionStateListener
- action
- action to be executed for matching events
Type:ConnectionStateChange
- &block
- listener block that is yielded to for matching events
- call
- called with matching events
Example
Browser ConnectionState
change example
onceOnce
There are two overloaded versions of this method:
once(String event, listener(ConnectionStateChange stateChange))once(ConnectionEvent *event) → yields ConnectionStateChangevoid once(ConnectionEvent event, ConnectionStateListener listener)once(event: ARTRealtimeConnectionEvent, call: (ARTConnectionStateChange?) → Void) → ARTEventListenervoid Once(ConnectionEvent event, Action<ConnectionStateChange> action)
Register the given listener blockfunctionaction for a single occurrence of the specified ConnectionEvent on the Connection
. Once the listener has been called, it is removed as a registered listener and will not be called again. The listener is passed a ConnectionStateChange object that contains the current state, previous state, the event, and an optional reason for the state change. (For the update
event, the current and previous states will be the same).
once(listener(ConnectionStateChange stateChange))once → yields ConnectionStateChangevoid once(ConnectionStateListener listener)once(call: (ARTConnectionStateChange?) → Void) → ARTEventListenervoid Once(Action<ConnectionStateChange> action)
Register the given listener blockaction for a single occurrence of any ConnectionEvent on the Connection
. Once the listener has been called, it is removed as a registered listener and will not be called again. The listener is passed a ConnectionStateChange object that contains the current state, previous state, and an optional reason for the state change. (For the update
event, the current and previous states will be the same).
If an exception is thrown in the listener and bubbles up to the event emitter, it will be caught and logged at error
level, so as not to affect other listeners for the same event
Parameters
- event(s)
- the connection event(s) to subscribe to
Type:String
orString[]
- event
- the connection event to subscribe to
Type:ConnectionEvent
- event
- the connection event to subscribe to
Type:ConnectionEvent
- event
- the connection event as a Symbol such as
:connected
orConnectionEvent
object to subscribe to
Type:ConnectionEvent
- event
- the connection event to subscribe to
Type:ARTRealtimeConnectionEvent
- listener
- is a function of the form
function(stateChange)
to be notified for a single occurrence of a matching event - listener
- listener to be notified for a single occurrence of a matching state change
Type:ConnectionStateListener
- action
- action to be executed for matching state changes
Type:ConnectionStateChange
- &block
- listener block that is yielded to for a single occurrence of a matching event
- call
- called with matching events
offOff
There are sixtwo overloaded versions of this method:
off(String event, listener)off(ConnectionEvent *event, &block)void off(ConnectionEvent event, ConnectionStateListener listener)off(event: ARTRealtimeConnectionEvent, listener: ARTEventListener)void Off(ConnectionEvent event, Action<ConnectionStateChange> action)
Remove the given listener blockaction for the ConnectionEvent.
off(listener)off(&block)void off(ConnectionStateListener listener)off(listener: ARTEventListener)void Off(Action<ConnectionStateChange> action)
Remove the given listener blockaction for all ConnectionEvents
off(String[] states, listener)
Removes the given listener from all ConnectionEvents in the array.
off(String state)
Removes all listeners for a given @ConnectionEvent@s.
off(String[] states)
Removes all listeners for all ConnectionEvents in the array.
off()
Removes all listeners (including both those registered against specific events and those registered without an event).
Parameters
- event(s)
- the connection event(s) to unsubscribe from
Type:String
orString[]
- event
- the connection event to unsubscribe from
Type:ConnectionEvent
- event
- the connection event to subscribe to
Type:ConnectionEvent
- event
- the connection event as a Symbol such as
:connected
orConnectionEvent
object to unsubscribe from
Type:ConnectionEvent
- event
- the connection event to unsubscribe from
Type:ARTRealtimeConnectionEvent
- listener
- is the listener function to be removed
- listener
- is the listener to be removed
Type:ConnectionStateListener
- action
- action to be executed for matching event changes
Type:ConnectioneventChangeEventArgs
- &block
- is the listener block to be removed
- listener
- previous return value from a
on
oronce
call
streamSubscription
obtained from calling on
can be used to cancel a listener by calling streamSubscription.cancel
.
pingPing
ping(callback(ErrorInfo err, Number responseInMilliseconds))Deferrable ping → yields
Float seconds
void ping(CompletionListener listener)ping(callback: (ARTErrorInfo?) → Void)void Ping(Action<TimeSpan?, ErrorInfo> callback)
When connected, sends a heartbeat ping to the Ably server and executes the callback with any error and the response time in millisecondsexecutes the callbackcalls the listeneryields the elapsed time in seconds when a heartbeat ping request is echoed from the server. This can be useful for measuring true round-trip latency to the connected Ably server.
Returns
A Deferrable
object is returned from this method.
On successfully echoing a heartbeat from Ably, the registered success blocks for the Deferrable
and any block provided to this method yields a Float
representing the time in seconds for the heartbeat ping request to be echoed.
Failure to receive a heartbeat ping will trigger the errback callbacks of the Deferrable
with an ErrorInfo
object containing an error response as defined in the Ably REST API documentation.
Related types
io.ably.lib.realtime.CompletionListener
A io.ably.lib.realtime.CompletionListener
is an interface allowing a client to be notified of the outcome of an asynchronous operation.
public interface CompletionListener {
// Called when the associated operation completes successfully,
public void onSuccess();
// Called when the associated operation completes with an error.
public void onError(ErrorInfo reason);
}
ConnectionStateARTRealtimeConnectionStateConnection::STATE Enumio.ably.lib.realtime.ConnectionState EnumIO.Ably.Realtime.ConnectionState Enumably.ConnectionState Enum
ConnectionState
is a String with a value matching any of the Realtime Connection
states.
var ConnectionStates = [
'initialized',
'connecting',
'connected',
'disconnected',
'suspended',
'closing',
'closed',
'failed'
]
io.ably.lib.realtime.ConnectionState
is an enum representing all the Realtime Connection
states.
public enum ConnectionState {
initialized, // 0
connecting, // 1
connected, // 2
disconnected, // 3
suspended, // 4
closing, // 5
closed, // 6
failed // 7
}
IO.Ably.Realtime.ConnectionState
is an enum representing all the Realtime Connection
states.
public enum ConnectionState
{
Initialized, //0
Connecting, //1
Connected, //2
Disconnected, //3
Suspended, //4
Closing, //5
Closed, //6
Failed //7
};
Ably::Realtime::Connection::STATE
is an enum-like value representing all the Realtime Connection
states. STATE
can be represented interchangeably as either symbols or constants.
Symbol states
:initialized # => 0
:connecting # => 1
:connected # => 2
:disconnected # => 3
:suspended # => 4
:closing # => 5
:closed # => 6
:failed # => 7
Constant states
Connection::STATE.Initialized # => 0
Connection::STATE.Connecting # => 1
Connection::STATE.Connected # => 2
Connection::STATE.Disconnected # => 3
Connection::STATE.Suspended # => 4
Connection::STATE.Closing # => 5
Connection::STATE.Closed # => 6
Connection::STATE.Failed # => 7
Example usage
# Example with symbols
client.connection.on(:connected) { ... }
# Example with constants
client.connection.on(Ably::Realtime::Connection::STATE.Connected) { ... }
# Interchangeable
Ably::Realtime::Connection::STATE.Connected == :connected # => true
ARTRealtimeConnectionState
is an enum representing all the Realtime Connection
states.
typedef NS_ENUM(NSUInteger, ARTRealtimeConnectionState) {
ARTRealtimeInitialized,
ARTRealtimeConnecting,
ARTRealtimeConnected,
ARTRealtimeDisconnected,
ARTRealtimeSuspended,
ARTRealtimeClosing,
ARTRealtimeClosed,
ARTRealtimeFailed
};
public enum ARTRealtimeConnectionState : UInt {
case Initialized
case Connecting
case Connected
case Disconnected
case Suspended
case Closing
case Closed
case Failed
}
ConnectionState
is an enum representing all the Realtime Connection
states.
const (
StateConnInitialized = 1
StateConnConnecting = 2
StateConnConnected = 4
StateConnDisconnected = 8
StateConnSuspended = 16
StateConnClosing = 32
StateConnClosed = 64
StateConnFailed = 128
)
ably.ConnectionState
is an enum representing all the Realtime Connection
states.
enum ConnectionState {
initialized,
connecting,
connected,
disconnected,
suspended,
closing,
closed,
failed
}
ConnectionEventARTRealtimeConnectionEventConnection::EVENT Enumio.ably.lib.realtime.ConnectionEvent EnumIO.Ably.Realtime.ConnectionEvent Enumably.ConnectionEvent Enum
ConnectionEvent
is a String that can be emitted as an event on the Connection
object; either a Realtime Connection
state or an update
event.
var ConnectionEvents = [
'initialized',
'connecting',
'connected',
'disconnected',
'suspended',
'closing',
'closed',
'failed',
'update'
]
io.ably.lib.realtime.ConnectionEvent
is an enum representing all the events that can be emitted be the Connection
; either a Realtime Connection
state or an update
event.
public enum ConnectionEvent {
initialized, // 0
connecting, // 1
connected, // 2
disconnected, // 3
suspended, // 4
closing, // 5
closed, // 6
failed, // 7
update // 8
}
IO.Ably.Realtime.ConnectionEvent
is an enum representing all the events that can be emitted be the Connection
; either a Realtime Connection
state or an Update
event.
public enum ConnectionState
{
Initialized, //0
Connecting, //1
Connected, //2
Disconnected, //3
Suspended, //4
Closing, //5
Closed, //6
Failed, //7
update //8
};
Ably::Realtime::Connection::EVENT
is an enum-like value representing all the events that can be emitted be the Connection
; either a Realtime Connection
state or an :update
event. EVENT
can be represented interchangeably as either symbols or constants.
Symbol states
:initialized # => 0
:connecting # => 1
:connected # => 2
:disconnected # => 3
:suspended # => 4
:closing # => 5
:closed # => 6
:failed # => 7
:update # => 8
Constant states
Connection::EVENT.Initialized # => 0
Connection::EVENT.Connecting # => 1
Connection::EVENT.Connected # => 2
Connection::EVENT.Disconnected # => 3
Connection::EVENT.Suspended # => 4
Connection::EVENT.Closing # => 5
Connection::EVENT.Closed # => 6
Connection::EVENT.Failed # => 7
Connection::EVENT.Update # => 8
Example usage
# Example with symbols
client.connection.on(:connected) { ... }
# Example with constants
client.connection.on(Ably::Realtime::Connection::STATE.Connected) { ... }
# Interchangeable
Ably::Realtime::Connection::STATE.Connected == :connected # => true
ARTRealtimeConnectionEvent
is an enum representing all the events that can be emitted be the Connection
; either a Realtime Connection
state or an Update
event.
typedef NS_ENUM(NSUInteger, ARTRealtimeConnectionEvent) {
ARTRealtimeConnectionEventInitialized,
ARTRealtimeConnectionEventConnecting,
ARTRealtimeConnectionEventConnected,
ARTRealtimeConnectionEventDisconnected,
ARTRealtimeConnectionEventSuspended,
ARTRealtimeConnectionEventClosing,
ARTRealtimeConnectionEventClosed,
ARTRealtimeConnectionEventFailed,
ARTRealtimeConnectionEventUpdate
};
public enum ARTRealtimeConnectionEvent : UInt {
case Initialized
case Connecting
case Connected
case Disconnected
case Suspended
case Closing
case Closed
case Failed
case Update
}
ConnectionEvent
is a String that can be emitted as an event on the Connection
object; either a Realtime Connection
state or an update
event.
const (
StateConnInitialized = 1
StateConnConnecting = 2
StateConnConnected = 4
StateConnDisconnected = 8
StateConnSuspended = 16
StateConnClosing = 32
StateConnClosed = 64
StateConnFailed = 128
)
ably.ConnectionEvent
is an enum representing all the events that can be emitted be the Connection
; either a Realtime Connection
state or an update
event.
enum ConnectionEvent {
initialized,
connecting,
connected,
disconnected,
suspended,
closing,
closed,
failed,
update
}
io.ably.lib.realtime.ConnectionStateListener
A io.ably.lib.realtime.ConnectionStateListener
is an interface allowing a client to be notified of connection state change. See Connection#on
to register a listener for one or more events.
public interface ConnectionStateListener {
// Called when the connection state changes
public void onConnectionStateChanged(ConnectionStateListener.ConnectionStateChange state);
}
ConnectionStateChange ObjectARTConnectionStateChangeio.ably.lib.realtime.ConnectionStateListener.ConnectionStateChangeConnectionStateChangeIO.Ably.Realtime.ConnectionStateChangeably.ConnectionStateChange
A io.ably.lib.realtime.ConnectionStateListener.ConnectionStateChange
Ably::Models::ConnectionStateChange
ARTConnectionStateChange
IO.Ably.Realtime.ConnectionStateChange
ConnectionStateChange
is a type encapsulating state change information emitted by the Connection
object. See Connection#on
to register a listener for one or more events.
PropertiesMembersAttributes
- currentCurrent
- the new state
Type: StateString
Connection::STATE
ConnectionState
- previousPrevious
- the previous state. (for the
update
event, this will be equal to thecurrent
state)
Type: StateString
Connection::STATE
ConnectionState
- eventEvent
- the event that triggered this state change
Type:ConnectionEvent
Connection::EVENT@ - reasonReason
- an
ErrorInfo
containing any information relating to the transition
Type:ErrorInfo
- retryInretry_inRetryIn
- Duration upon which the library will retry a connection where applicable, as millisecondssecondsa
Timespan
Type:Integer
Timespan
Long Integer
LastConnectionDetails
A LastConnectionDetails
object provides details on the last connection in a browser environment persisted when the window beforeunload
fired. This object is provided to the callback specified in the recover
attribute of ClientOptions
. The callback in turn instructs the client library whether the connection should be recovered or not. See connection state recovery for more information.
Please note that as sessionStorage
is used to persist the LastConnectionDetails
between page reloads, it is only available for pages in the same origin and top-level browsing context.
Properties
- recoveryKey
- An opaque string obtained from the recoveryKey attribute of the Connection object before the page was unloaded. This property is used by the library to recover the connection
Type:String
- disconnectedAt
- the time at which the previous library was abruptly disconnected before the page was unloaded. This is represented as milliseconds since epoch
Type:Integer
- location
- a clone of
location
object of the previous page’sdocument
object before the page was unloaded. A common use case for this attribute is to ensure that the previous page URL is the same as the current URL before allowing the connection to be recovered. For example, you may want the connection to be recovered only for page reloads, but not when a user navigates to a different page
Type:String
- clientId
- the
clientId
of the client’s Auth object before the page was unloaded. A common use case for this attribute is to ensure that the current logged in user’sclientId
matches the previous connection’sclientId
before allowing the connection to be recovered. Ably prohibits changing aclientId
for an existing connection, so any mismatch inclientId
during a recover will result in the connection moving to the failed state
Type:String