Messages
The Ably Realtime service allows for clients to send information with messages
, which contain data the client wishes to communicate. These messages are published through channels, which other users can subscribe to in order to receive them. This scalable and resilient messaging pattern is commonly called pub/sub.
Getting started
The Ably Realtime client library provides a straightforward API for publishing and subscribing to messages on a channel. If the channel does not exist at the time the client is attached, a channel will be created in the Ably system immediately.
var realtime = new Ably.Realtime('<loading API key, please wait>');
var channel = realtime.channels.get('aft-hip-jab');
channel.subscribe(function(message) {
alert('Received: ' + message.data);
});
channel.publish('example', 'message data');
Demo OnlyCopyCopied!
If you would prefer to just dive into code and see some examples of how to use messages, then we recommend you take a look at our Realtime tutorials.
Messages
Each message published has an optional event name
property and a data
property carrying the payload of the message. Various primitive and object types are defined, portable and supported in all clients, enabling clients to be interoperable despite being hosted in different languages or environments.
The supported payload types are Strings, objects or arrays capable of JSON representation, buffers containing arbitrary binary data, and Nulls. Client libraries will detect the supplied message payload and encode the message appropriately. (Note that if sending a binary, that binary should be the entire payload; an object with a binary field within it may not be correctly encoded).
Subscribing to messages
The name
property of published messages does not affect the distribution of a channel message to clients but may be used as a (purely client-side) subscription filter, allowing a client to register a listener that only sees a subset of the messages received on the channel. When subscribing, a message listener can subscribe to see all messages on the channel or only a subset whose name matches a given name
string.
The client can choose whether or not to receive messages that they themselves publish using ClientOptions#echoMessages
.
A client can subscribe to all messages on a channel by passing a listener function to the subscribe
method. The listener is passed a Message
object for each message received.
channel.subscribe(function(message) {
console.log('message received for event ' + message.name);
console.log('message data:' + message.data);
});
CopyCopied!
Alternatively a listener may be registered so that it is called only for messages having a specific event name.
channel.subscribe('myEvent', function(message) {
console.log('message received for event ' + message.name);
console.log('message data:' + message.data);
});
CopyCopied!
Previously registered listeners can be removed individually or all together.
/* remove the listener registered for a single event */
channel.unsubscribe('myEvent', myListener);
/* remove the listener registered for all events */
channel.unsubscribe(myListener);
CopyCopied!
Publishing messages
Channels expose a publish
method whereby a client can publish either a single message or an array of messages to a channel. A listener optionally passed in to the publish
method enables the client to know whether or not the operation succeeded.
channel.publish('event', 'This is my payload', function(err) {
if(err) {
console.log('Unable to publish message; err = ' + err.message);
} else {
console.log('Message successfully sent');
}
});
CopyCopied!
Channels also expose an async version PublishAsync
of the Publish
call which resumes execution once the message is confirmed received. It is purely for convenience.
Result result = await channel.PublishAsync("event", "payload");
if(result.IsFailure) {
Console.WriteLine("Unable to publish message. Reason: " + result.Error.Message);
} else {
Console.WriteLine("Message published successfully");
}
CopyCopied!
Batch publishing
It is common for a single message to be intended for multiple channels. With a realtime connection, you can effectively send a message to multiple channels at once by allowing multiple concurrent publish operations. If you wish to send a message to multiple channels within a single operation, you can make use of the REST batch API.
Retrieving message history
Channels expose a history
method providing a means for clients to obtain messages previously sent on the channel. Channel history can be used to return continuous message history up to the exact point a realtime channel was attached.
History provides access to instantaneous “live” history as well as the longer term persisted history for attached channels. If persisted history is enabled for the channel, then messages will typically be stored for 24 – 72 hours. If persisted history is not enabled, Ably retains the last two minutes of message history in memory.
The following example retrieves the first two pages of historical messages published up until the point the channel was attached.
channel.attach(function() {
channel.history({ untilAttach: true }, function(err, resultPage) {
if(err) {
console.log('Unable to get channel history; err = ' + err.message);
} else {
console.log(resultPage.items.length + ' messages received in first page');
if(resultPage.hasNext()) {
resultPage.next(function(err, nextPage) { ... });
}
}
});
});
CopyCopied!
See the history documentation for further details of the supported query parameters.
Message interactions
Message interactions are currently only supported by the Ably JavaScript SDK. To read more about message interactions please refer to the message interactions docs.
API Reference
View the Messages API Reference.