Message Basics
PubNub's messaging system is the backbone of real-time data flow, enabling the delivery and processing of messages within milliseconds.
Send messages
Messages are dispatched using the Publish API, designed to minimize latency and maximize delivery reliability across global infrastructures. You can send messages to individual channels, using JSON format for structured data.
pubnub.publish(
{
channel: "my_channel",
message: {"text": "Hello World!"}
},
function(status, response) {
console.log(status, response);
}
);
Messages can include metadata for additional context. You can only publish to one channel at a time. For any multi-channel operations, use channel groups.
The maximum message size in PubNub is 32 KB. This limit includes the channel name, and any metadata associated with the message. If the published message exceeds this size, an error will be returned. This constraint ensures efficient delivery and network usage.
Signals
Signals are lightweight, one-way notifications ideal for high-frequency, low-cost operations like typing indicators or real-time location updates. These differ from standard messages, for example by not supporting Message Persistence or Mobile Push Notifications.
For more differences, check the Messages vs Signals section.
Receive messages
To receive messages, implement an event listener within your application using an SDK of your choice. Event handlers process various message types, enabling your app to react to incoming data dynamically.
const subscription = pubnub.channel('channel_1').subscription();
subscription.onMessage = (messageEvent) => { console.log("Message event: ", messageEvent); };
subscription.onPresence = (presenceEvent) => { console.log("Presence event: ", presenceEvent); };
Message reactions
Message reactions allow you to add actions such as delivery acknowledgments or emojis to messages post-publication. You can easily add or remove these reactions to improve user interaction, for example in chat messages.
pubnub.addMessageAction(
{
channel: 'chats.room1',
messageTimetoken: '15610547826970040',
action: {
type: 'reaction',
value: 'smiley_face',
}
},
function(status, response) {
console.log(status, response);
}
);
Message types
Using descriptive message types helps in differentiating and processing various message categories. Define custom_message_type
for every message, enabling targeted handling and data management.