Connection

The Connection interface represents the connection to Ably and provides methods to inspect the connection state, listen for state changes, and explicitly open or close the connection. Access it via the connection property of a Realtime client instance.

JavaScript

1

const connection = realtime.connection;

Properties

The Connection interface has the following properties:

idString
A unique public identifier for this connection, used to identify this member in presence events and messages.
stateConnectionState
The current connection state of this connection.
errorReasonErrorInfo or Undefined
When a connection failure occurs this property contains the error reason.
keyString
A unique private connection key used to recover or resume a connection, assigned by Ably. When recovering a connection explicitly, the recoveryKey is used in the clientOptions.recover option 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 realtime client.

Connect to Ably

connection.connect(): void

Explicitly calling connect() is unnecessary unless clientOptions.autoConnect is false. Unless already connected or connecting, this method causes the connection to open, entering the connecting state.

JavaScript

1

2

realtime.connection.connect();
await realtime.connection.once('connected');

Close the connection

connection.close(): void

Causes the connection to close, entering the closing state. Once closed, the SDK will not attempt to re-establish the connection without an explicit call to connect().

JavaScript

1

realtime.connection.close();

Register a state change listener

connection.on(event: ConnectionEvent, listener: connectionEventCallback): void

Register the given listener for the specified ConnectionEvent 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.

connection.on(events: ConnectionEvent[], listener: connectionEventCallback): void

Registers the listener for each event in the array.

connection.on(listener: connectionEventCallback): void

Register the given listener 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.

JavaScript

1

2

3

4

5

6

7

realtime.connection.on('connected', (stateChange) => {
  console.log('Connected to Ably');
});

realtime.connection.on(['disconnected', 'suspended'], (stateChange) => {
  console.log('Connection lost:', stateChange.reason);
});

Parameters

The on() method takes the following parameters:

eventoptionalConnectionEvent
A single connection event to listen for.
eventsoptionalConnectionEvent[]
An array of connection events to listen for.
listenerrequiredconnectionEventCallback
A function notified for each matching event. If neither event nor events is supplied, it fires for every event.

Register a one-time state change listener

connection.once(event: ConnectionEvent, listener: connectionEventCallback): void

Register the given listener 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.

connection.once(listener: connectionEventCallback): void

Register the given listener for a single occurrence of any ConnectionEvent on the Connection.

connection.once(event: ConnectionEvent): Promise<ConnectionStateChange>

Returns a promise that is fulfilled with the next ConnectionStateChange for the specified event. This is the preferred way to await a specific connection state from async code.

connection.once(): Promise<ConnectionStateChange>

Returns a promise that is fulfilled with the next ConnectionStateChange, regardless of the event type.

JavaScript

1

2

await realtime.connection.once('connected');
console.log('Connected');

Parameters

The once() method takes the following parameters:

eventoptionalConnectionEvent
The connection event to listen for. If omitted, the listener fires for any event.
listeneroptionalconnectionEventCallback
A function notified for the next occurrence of the matching event. Omit to return a promise instead.

Returns

The callback-based overloads return void.

The promise-based overloads return Promise<ConnectionStateChange>. The promise is fulfilled with a ConnectionStateChange object the next time a matching event occurs, or rejected with an ErrorInfo object if the connection enters a state from which the event cannot occur.

Remove a state change listener

connection.off(event: ConnectionEvent, listener: connectionEventCallback): void

Remove the given listener for the specified ConnectionEvent.

connection.off(listener: connectionEventCallback): void

Remove the given listener for all ConnectionEvents.

connection.off(): void

Removes all listeners, including those registered with and without specific events.

JavaScript

1

2

3

4

5

6

7

8

const listener = (stateChange) => console.log(stateChange.current);
realtime.connection.on('connected', listener);

// Remove the specific listener for 'connected'
realtime.connection.off('connected', listener);

// Remove all listeners
realtime.connection.off();

Parameters

The off() method takes the following parameters:

eventoptionalConnectionEvent
The connection event to unsubscribe from. If omitted, the listener is removed from all events.
listeneroptionalconnectionEventCallback
The listener function to remove. If omitted, all listeners are removed.

Ping the Ably service

connection.ping(): Promise<number>

When connected, sends a heartbeat ping to the Ably server and returns the round-trip time in milliseconds when a heartbeat ping response is received from the server. Useful for measuring the true round-trip latency to the connected Ably server.

JavaScript

1

2

const latency = await realtime.connection.ping();
console.log(`Latency: ${latency}ms`);

Returns

Promise<number>

Returns a promise. The promise is fulfilled with a number representing the time in milliseconds for the heartbeat ping request to be echoed, or rejected with an ErrorInfo object that details the reason why it was rejected.

Get registered listeners

connection.listeners(eventName?: ConnectionEvent): null | connectionEventCallback[]

Returns the listeners registered for the specified ConnectionEvent. If eventName is omitted, returns all registered listeners.

Parameters

The listeners() method takes the following parameters:

eventNameoptionalConnectionEvent
The connection event to filter listeners by.

Returns

null | connectionEventCallback[]

Returns an array of registered listener functions, or null if no listeners are registered for the specified event.

Wait for a connection state

connection.whenState(targetState: ConnectionState): Promise<null | ConnectionStateChange>

If the connection is already in the given state, returns a promise which immediately resolves to null. Otherwise calls once() to return a promise which resolves the next time the connection transitions to the given state.

JavaScript

1

await realtime.connection.whenState('connected');

Parameters

The whenState() method takes the following parameters:

targetStaterequiredConnectionState
The connection state to wait for.

Returns

Promise<null | ConnectionStateChange>

Returns a promise. If the connection is already in the given state, the promise immediately resolves to null. Otherwise it resolves with a ConnectionStateChange the next time the connection transitions to that state.

Create a connection recovery key

connection.createRecoveryKey(): null | string

Generates a string that can be used by another client to recover the current connection's state using clientOptions.recover, as described in the connection state recovery options.

JavaScript

1

const recoveryKey = realtime.connection.createRecoveryKey();

Returns

null | string

Returns a recovery key string, or null if a recovery key cannot be generated (for example, if the connection has never been connected).