Please be aware that you are viewing our bleeding edge unstable documentation. Unless you wanted to view the bleeding edge (and possibly unstable) documentation, we recommend you use our stable docs.

Go to Ably's stable canonical documentation »

I know what I'm doing, let me see the bleeding edge docs »

You are viewing our bleeding edge unstable documentation. We recommend you use our stable documentation »
Fork me on GitHub

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('{{API_KEY}}');
var channel = realtime.channels.get('{{RANDOM_CHANNEL_NAME}}');
channel.subscribe(function(message) {
  alert('Received: ' + message.data);
});
channel.publish('example', 'message data');
var Ably = require('ably');
var realtime = new Ably.Realtime('{{API_KEY}}');
var channel = realtime.channels.get('{{RANDOM_CHANNEL_NAME}}');
channel.subscribe(function(message) {
  console.log("Received: "  message.data);
});
channel.publish("example", "message data");
realtime = Ably::Realtime.new('{{API_KEY}}')
channel = realtime.channels.get('{{RANDOM_CHANNEL_NAME}}')
channel.subscribe do |message|
  puts "Received: #{message.data}"
end
channel.publish 'example', 'message data'
AblyRealtime realtime = new AblyRealtime("{{API_KEY}}");
Channel channel = realtime.channels.get("{{RANDOM_CHANNEL_NAME}}");
channel.subscribe(new MessageListener() {
  @Override
  public void onMessage(Message message) {
    System.out.println("New messages arrived. " + message.name);
  }
});
channel.publish("example", "message data");
AblyRealtime realtime = new AblyRealtime("{{API_KEY}}");
var channel = realtime.Channels.Get("{{RANDOM_CHANNEL_NAME}}");
channel.Subscribe(message => {
  Console.WriteLine($"Message: {message.name}:{message.data} received")
});
channel.Publish("example", "message data");
ARTRealtime *realtime = [[ARTRealtime alloc] initWithKey:@"{{API_KEY}}"];
ARTRealtimeChannel *channel = [realtime.channels get:@"{{RANDOM_CHANNEL_NAME}}"];
[channel subscribe:^(ARTMessage *message) {
    NSLog(@"Received: %@", message.data);
}];
[channel publish:@"example" data:@"message data"];
let realtime = ARTRealtime(key: "{{API_KEY}}")
let channel = realtime.channels.get("{{RANDOM_CHANNEL_NAME}}")
channel.subscribe { message in
    print("Received: \(message.data)")
}
channel.publish("example", data: "message data")

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 propertymemberattribute and a data propertymemberattribute 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, JSON objects and arrays, buffers containing arbitrary binary data, and Null objects. Client libraries detect the supplied message payload and encode the message appropriately.

Subscribing to messages

The name propertymemberattribute 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#echoMessagesClientOptions#echo_messages.

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.


A client can register for messages on a channel by implementing MessageListener and calling the subscribe(MessageListener listener) or subscribe(String name, MessageListener listener) method. The listener is passed an array of one or more Message objects when messages are received.


A client can subscribe to all messages on a channel by passing a block to the subscribe method. The block is passed a Message object for each message are received.


A client can subscribe to all messages on a channel by passing a lambda expression to the Subscribe method. The lambda is passed a Message object for each message are received.

channel.subscribe(function(message) {
  console.log('message received for event ' + message.name);
  console.log('message data:' + message.data);
});
channel.subscribe(function(message) {
  console.log('message received for event ' + message.name);
  console.log('message data:' + message.data);
});
channel.subscribe(new MessageListener() {
  @Override
  public void onMessage(Message message) {
    System.out.println("Message received: " + message.data);
  }
});
channel.Subscribe(message =>
{
    Console.WriteLine($"message received for event {message.Name}");
    Console.WriteLine($"message data: {message.Data}");
});
channel.subscribe do |message|
  puts "message received for event #{message.name}"
  puts "message data: #{message.data}"
end
[channel subscribe:^(ARTMessage *message) {
    NSLog(@"message received for event %@", message.name);
    NSLog(@"message data: %@", message.data);
}];
channel.subscribe { message in
    print("message received for event \(message.name)")
    print("message data: \(message.data)")
}

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);
});
channel.subscribe('myEvent', function(message) {
  console.log('message received for event ' + message.name);
  console.log('message data:' + message.data);
});
channel.subscribe("myEvent", new MessageListener() {
  @Override
  public void onMessage(Message message) {
    System.out.println("Message received: " + message.data);
  }
});
channel.Subscribe("myEvent", message =>
{
    Console.WriteLine($"message received for event {message.Name}");
    Console.WriteLine($"message data: {message.Data}");
});
channel.subscribe('myEvent') do |message|
  puts "message received for event #{message.name}"
  puts "message data: #{message.data}"
end
channel.subscribe("myEvent") { message in
    print("message received for event \(message.name)")
    print("message data: \(message.data)")
}
[channel subscribe:@"myEvent" callback:^(ARTMessage *message) {
    NSLog(@"message received for event %@", message.name);
    NSLog(@"message data: %@", message.data);
}];

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);
/* remove the listener registered for a single event */
channel.unsubscribe('myEvent', myListener);

/* remove the listener registered for all events */
channel.unsubscribe(myListener);
/* remove a single listener */
channel.unsubscribe(myListener);

/* remove the listener registered for all events */
channel.unsubscribe("myEvent", myListener);
/* remove a single listener */
channel.Unsubscribe(myHandler);

/* remove the listener registered for all events */
channel.Unsubscribe("myEvent", myHandler);
# remove the listener proc registered for a single event
channel.unsubscribe("myEvent", &my_proc)

# remove the listener proc registered for all events
channel.unsubscribe(&my_proc)
// remove the listener registered for a single event
[channel unsubscribe:@"myEvent" listener:listener];

// remove the listener registered for all events
[channel unsubscribe:listener];
// remove the listener registered for a single event
channel.unsubscribe("myEvent", listener: listener)

// remove the listener registered for all events
channel.unsubscribe(listener)

Publishing messages

Channels expose a publishPublish 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 publishPublish 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');
  }
});
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');
  }
});
deferrable = channel.publish('event', 'This is my payload') do
  puts 'Messages successfully sent'
end
deferrable.errback do |err|
  puts "Unable to publish messages; err = #{err}"
end
channel.publish("event", "This is my payload", new CompletionListener() {
  @Override
  public void onError(ErrorInfo reason) {
    System.out.println("Unable to publish message; err = " + reason.message);
  }
  @Override
  public void onSuccess() {
    System.out.println("Message successfully sent");
  }
});
channel.Publish("event", "payload", (success, error) =>
{
  if (error != null) {
    Console.WriteLine("Unable to publish message. Reason: " + error.Message);
  } else {
    Console.WriteLine("Message published successfully");
  }
});
[channel publish:@"event" data:@"This is my payload" callback:^(ARTErrorInfo *error) {
  if (error) {
    NSLog(@"Unable to publish message; err = %@", error.message);
  } else {
    NSLog(@"Message successfully sent");
  }
}];
channel.publish("event", data: "This is my payload") { error in
  if let error = error {
    print("Unable to publish message; err = \(error.message)")
  } else {
    print("Message successfully sent")
  }
}

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");
}

Retrieving message history

Channels expose a historyHistory 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) { ... });
      }
    }
  });
});
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) { ... });
      }
    }
  });
});
Param[] options = new Param[]{ new Param("untilAttach", "true") };
PaginatedResult<Message> resultPage = channel.history(options);
System.out.println(resultPage.items().length + " messages received in first page");
if(resultPage.hasNext()) {
  PaginatedResult<Message> nextPage = resultPage.next();
  System.out.println(nextPage.items().length + " messages received in second page");
}
PaginatedResult<Message> history = await channel.HistoryAsync(untilAttach: true);
Console.WriteLine($"{history.Items.Count} messages received in the first page");
if (history.HasNext)
{
  PaginatedResult<Message> nextPage = await history.NextAsync();
  Console.WriteLine($"{nextPage.Items.Count} messages received in the second page");
}
channel.attach do
  channel.history(until_attach: true) do |result_page|
    puts "#{result_page.items.length} messages received in first page"
    if result_page.has_next?
      result_page.next { |next_page| ... }
    end
  end
end
[channel attach:^(ARTErrorInfo *error) {
    ARTRealtimeHistoryQuery *query = [[ARTRealtimeHistoryQuery alloc] init];
    query.untilAttach = true;
    [channel history:query callback:^(ARTPaginatedResult<ARTMessage *> *resultPage, ARTErrorInfo *error) {
        NSLog(@"%lu messages received in first page", (unsigned long)[resultPage.items count]);
        if (resultPage.hasNext) {
            [resultPage next:^(ARTPaginatedResult<ARTMessage *> *nextPage, ARTErrorInfo *error) {
                // ...
            }];
        }
    } error:nil];
}];
channel.attach { error in
    let query = ARTRealtimeHistoryQuery()
    query.untilAttach = true
    try! channel.history(query) { resultPage, error in
        let resultPage = resultPage!
        print("\(resultPage.items.count) messages received in first page")
        if resultPage.hasNext {
            resultPage.next { nextPage, error in
                // ...
            }
        }
    }
}

See the history documentation for further details of the supported query parameters.

Message API Reference

PropertiesMembersAttributesAttributes

A Message represents an individual message that is sent to or received from Ably.

nameName

The event name, if provided.
Type: String

dataData

The message payload, if provided.
Type: String, StringBuffer, JSON ObjectString, ByteArray, JSONObject, JSONArrayString, byte[], plain C# object that can be serialized to JsonString, Binary (ASCII-8BIT String), Hash, ArrayString, Bytearray, Dict, ListString, Binary String, Associative Array, ArrayNSString *, NSData *, NSDictionary *, NSArray *String, NSData, Dictionary, Array

idId

A Unique ID assigned by Ably to this message.
Type: String

clientIdClientIdclient_idclient_id

The client ID of the publisher of this message.
Type: String

connectionIdConnectionIdconnection_idconnection_id

The connection ID of the publisher of this message.
Type: String

timestampTimestamp

Timestamp when the message was received by the Ably, as milliseconds since the epocha Time object
.Type: IntegerLong IntegerDateTimeOffsetTimeNSDate

encodingEncoding

This will typically be empty as all messages received from Ably are automatically decoded client-side using this value. However, if the message encoding cannot be processed, this attribute will contain the remaining transformations not applied to the data payload.
Type: String

Message methods

Message.fromEncoded

Message.fromEncoded(Object encodedMsg, ChannelOptions channelOptions?) → Message

A static factory method to create a Message from a deserialized Message-like object encoded using Ably’s wire protocol.

Parameters

encodedMsg
a Message-like deserialized object.
Type: Object
channelOptions
an optional ChannelOptions. If you have an encrypted channel, use this to allow the library can decrypt the data.
Type: Object

Returns

A Message object

Message.fromEncodedArray

Message.fromEncodedArray(Object[] encodedMsgs, ChannelOptions channelOptions?) → Message[]

A static factory method to create an array of Messages from an array of deserialized Message-like object encoded using Ably’s wire protocol.

Parameters

encodedMsgs
an array of Message-like deserialized objects.
Type: Array
channelOptions
an optional ChannelOptions. If you have an encrypted channel, use this to allow the library can decrypt the data.
Type: Object

Returns

An Array of Message objects


Back to top