Receive messages

Receiving messages is a two-fold process: you must subscribe to a channel (or multiple channels!) of your liking and handle incoming messages using a listener.

You can subscribe to hundreds of channels with a single call. There are many ways of subscribing so make sure you choose the optimal one for your use case.

// subscribe to a single channel
pubnub.subscribe({channels: ["chats_inbox.user_1905"]});

// subscribe to multiple channels
pubnub.subscribe({
channels: [
"chats_guilds.mages_guild",
"alerts.system",
"geolocation.data"
]
});

When you subscribe to a channel, the client starts to receive all messages sent to it. To act on the received data, you must implement an event listener.

The event listener is a single point through which your app receives all messages, signals, and events that are sent to any channel you are subscribed to. Each type of data sent to a channel has its own handler which is used to provide logic for what to do when the client receives a given message type. For example, you may want to simply display the content of the message or trigger custom business logic.

If you wanted to handle a different message type like a signal, you'd need to implement a signal handler in your listener. Each handler has its own set of available properties and is dedicated to a separate type of message you can send.

In the code below, the content and the publisher of each received message is handled by the message listener which prints them to the console.

pubnub.addListener({
message: function(receivedMessage) {
// handle message
console.log("The message text is: ", receivedMessage.message);
console.log("Sent by: ", receivedMessage.publisher);
}
});

You can enhance messages that have already been published by attaching emojis, reactions, or delivery acknowledgements.

Even though PubNub is all about real-time communication, you can persist and retrieve older messages, not just the ones being sent in real time.

On this page