Basic pub-sub
Ably Pub/Sub enables you to implement the publish-subscribe (pub-sub) pattern. Any number of publishers can send messages to a channel, and any number of subscribers can receive those messages. Publishers and subscribers are completely decoupled from one another.
Channels are used to separate messages into different topics. Messages contain the data that a client is communicating, such as the contents of an individual chat message, or an event that has occurred, such as updated financial information. Whilst billions of messages may be delivered by Ably, clients receive only the messages on the channels they subscribe to.
To get started with sending and receiving messages, all you need to do is:
Use a channel
Channels are used to separate your message traffic into different topics, and are identified by a unique name. Clients create or retrieve a channel and can then subscribe to them, and send messages to them.
Use the get() method to create or retrieve a channel instance:
1
const channel = pubsubDeviceClient.channels.get('arc-one-ego');Subscribe to a channel
Clients subscribe to a channel to receive the messages published to it. Clients can subscribe to all messages, or only messages identified by specific names.
Use the subscribe() method on a channel to receive any messages that are published to it.
The following is an example of subscribing to all messages on a channel:
1
2
3
4
5
const pubsubDeviceClient = createClient('demokey:*****');
const channel = pubsubDeviceClient.channels.get('arc-one-ego');
await channel.subscribe((message) => {
alert('Received: ' + message.data);
});The following is an example of only subscribing to messages with a specific name:
1
2
3
4
await channel.subscribe('myEvent', (message) => {
console.log('message received for event ' + message.name);
console.log('message data:' + message.data);
});Publish a message
Publishing messages to a channel is how clients communicate with one another. Any subscribers will receive published messages as long as they are subscribed and have the subscribe capability for that channel.
On a server, an Ably HTTP client is more appropriate for publishing if your use case doesn't require a persistent connection to Ably. For example, if you have a server publishing messages to channels that doesn't need to receive any updates from them.
Use the publish() method to send messages to a channel.
1
2
3
const pubsubDeviceClient = createClient('demokey:*****');
const channel = pubsubDeviceClient.channels.get('arc-one-ego');
await channel.publish('example', 'message data');