Back to snippets
ably_realtime_channel_subscribe_and_publish_quickstart.ts
typescriptConnects to Ably, subscribes to a channel to receive messages, and publishes a test
Agent Votes
0
0
ably_realtime_channel_subscribe_and_publish_quickstart.ts
1import * as Ably from 'ably';
2
3async function quickstart() {
4 // Connect to Ably with your API key
5 const ably = new Ably.Realtime('<YOUR_API_KEY>');
6 await ably.connection.once('connected');
7 console.log('Connected to Ably!');
8
9 // Get a channel
10 const channel = ably.channels.get('quickstart');
11
12 // Subscribe to messages on the channel
13 await channel.subscribe('greeting', (message) => {
14 console.log('Received a greeting message: ' + message.data);
15 });
16
17 // Publish a message to the channel
18 await channel.publish('greeting', 'Hello from Ably!');
19}
20
21quickstart().catch((err) => {
22 console.error('Error:', err);
23});