Receive Messages
Messages sent through PubNub are PubNub events with a message payload. They are only structured differently.
Channels are unique identifiers that carry real-time messages between publishers and subscribers. See channels for details.
Receiving messages (and other events) is a three-step process:
- Create an entity-based subscription or a subscription set.
- Implement the appropriate event listener.
- Subscribe to the subscription to receive real-time updates.
Entity-enabled SDKs
Not all PubNub SDKs support entities yet. For SDKs that still use legacy event listeners and the Subscribe API, see their SDK API docs.
Refer to the API documentation of each SDK for more information.
Add an event handler
Messages and events are received using a listener (a callback function). In the listener, add logic for messages, signals, files, presence, and other events.
Add listeners to subscriptions and subscription sets to handle one or many subscriptions.
There are four entities:
Each message or event type has its own handler where you implement app logic for the received data.
Subscription with Presence
To receive Presence events, you subscribe with Presence and have Presence enabled on your keyset. Make sure you configure Presence to track Presence-related events for all or selected channels (through Presence Management rules).
When you no longer need to handle events, remove the listener using the SDK method. See JavaScript SDK as an example.
You can receive events using the following approaches:
- Using on[Event] handlers
- Using addListener() method
You can assign functions directly to event-specific properties on the subscription object. This approach provides a clean, straightforward way to handle specific events.
const channelSubscription = pubnub.channel('channel_name').subscription();
channelSubscription.subscribe();
// Handle messages
channelSubscription.onMessage = function(message) {
console.log('Received message:', message);
};
// Handle presence events
channelSubscription.onPresence = function(presenceEvent) {
console.log('Presence event:', presenceEvent);
};
// Other handlers are available for signals, objects, files, and message actions
This method allows for clear, direct assignment of handlers to specific event types and is particularly useful when you want to add or change handlers dynamically.
For more information on how to use the on[Event]
syntax, refer to each SDK's API documentation, for example, JavaScript.
This approach is more similar to the previous SDK versions and lets you define all event handlers in a single call. This can be more familiar if you're upgrading from earlier versions.
channelSubscription.addListener({
// Handle messages
message: (message) => {
console.log('Received message:', message);
},
// Handle presence events
presence: (presenceEvent) => {
console.log('Presence event:', presenceEvent);
},
// Other event handlers for signals, objects, files, message actions
});
The addListener()
method is convenient when setting up multiple event handlers at once and may be more familiar to developers who have used previous versions of PubNub SDKs.
For more information on how to use the addListener()
method, refer to each SDK's API documentation, for example, JavaScript.
The following handlers are available:
User ID / UUID
User ID is also referred to as UUID
/uuid
in some APIs and server responses but holds the value of the userId
parameter you set during initialization.
- JavaScript
- Swift
- Objective-C
- Java
- C#
- Go
- Python
- Dart
- Kotlin
// create a subscription from a channel entity
const channel = pubnub.channel('channel_1');
const subscription = channel.subscription();
// Event-specific listeners
subscription.onMessage = (messageEvent) => { console.log("Message event: ", messageEvent); };
subscription.onPresence = (presenceEvent) => { console.log("Presence event: ", presenceEvent); };
subscription.onMessage = (messageEvent) => { console.log("Message event: ", messageEvent); };
subscription.onPresence = (presenceEvent) => { console.log("Presence event: ", presenceEvent); };
subscription.onSignal = (signalEvent) => { console.log("Signal event: ", signalEvent); };
subscription.onObjects = (objectsEvent) => { console.log("Objects event: ", objectsEvent); };
subscription.onMessageAction = (messageActionEvent) => { console.log("Message Action event: ", messageActionEvent); };
subscription.onFile = (fileEvent) => { console.log("File event: ", fileEvent); };
// Generic listeners
show all 76 lines// Add event-specific listeners
// Add a listener to receive Message changes
subscription.onMessage = { message in
print("Message Received: \(message) Publisher: \(message.publisher ?? "defaultUUID")")
}
// Add a listener to receive Presence changes
subscription.onPresence = { presenceChange in
for action in presenceChange.actions {
switch action {
case let .join(uuids):
print("The following list of occupants joined at \(presenceChange.timetoken): \(uuids)")
case let .leave(uuids):
print("The following list of occupants left at \(presenceChange.timetoken): \(uuids)")
case let .timeout(uuids):
show all 81 lines// Listener's class should conform to `PNEventsListener` protocol
// in order to have access to available callbacks.
// Adding listener.
[pubnub addListener:self];
// Callbacks listed below.
- (void)client:(PubNub *)pubnub didReceiveMessage:(PNMessageResult *)message {
NSString *channel = message.data.channel; // Channel on which the message has been published
NSString *subscription = message.data.subscription; // Wild-card channel or channel on which PubNub client actually subscribed
NSNumber *timetoken = message.data.timetoken; // Publish timetoken
id msg = message.data.message; // Message payload
NSString *publisher = message.data.publisher; // Message publisher
}
show all 106 linespubnub.addListener(new StatusListener() {
// PubNub status
@Override
public void status(PubNub pubnub, PNStatus status) {
switch (status.getCategory()) {
/* case statements for various categories */
}
}
});
pubnub.addListener(new EventListener() {
// Messages
@Override
public void message(PubNub pubnub, PNMessageResult message) {
String messagePublisher = message.getPublisher();
show all 90 lines// Add event-specific listeners
// Add a listener to receive Message changes
Subscription subscription1 = pubnub.Channel("channelName").Subscription()
subscription1.OnMessage = (Pubnub pn, PNMessageResult<object> messageEvent) => {
Console.WriteLine($"Message received {messageEvent.Message}");
};
subscription1.Subscribe<object>()
// Add multiple listeners
SubscribeCallbackExt eventListener = new SubscribeCallbackExt(
delegate (Pubnub pn, PNMessageResult<object> messageEvent) {
Console.WriteLine($"received message {messageEvent.Message}");
show all 37 linesimport (
pubnub "github.com/pubnub/go"
)
listener := pubnub.NewListener()
go func() {
for {
select {
case signal := <-listener.Signal:
// Channel
fmt.Println(signal.Channel)
// Subscription
fmt.Println(signal.Subscription)
// Payload
show all 109 lines# Add event-specific listeners
# using closure for reusable listener
def on_message(listener):
def message_callback(message):
print(f"\033[94mMessage received on: {listener}: \n{message.message}\033[0m\n")
return message_callback
# without closure
def on_message_action(message_action):
print(f"\033[5mMessageAction received: \n{message_action.value}\033[0m\n")
def on_presence(listener):
def presence_callback(presence):
print(f"\033[0;32mPresence received on: {listener}: \t{presence.uuid} {presence.event}s "
show all 77 linessubscription.messages.listen((envelope) {
switch (envelope.messageType) {
case MessageType.normal:
print('${envelope.publishedBy} sent a message: ${envelope.content}');
print('${envelope.channel}'); //to display the channel that message was sent on
print('${envelope.publishedAt}'); // to display timetoken of the message received
print('${envelope.content}'); // to display content of the message
print('${envelope.uuid}'); // to display the User ID of the sender
break;
case MessageType.signal:
print('${envelope.publishedBy} sent a signal message: ${envelope.content}');
print('${envelope.channel}'); //to display the channel that message was sent on
print('${envelope.publishedAt}'); // to display timetoken of the message received
print('${envelope.content}'); // to display content of the message
print('${envelope.uuid}'); // to display the User ID of the sender
show all 55 linessubscription.onMessage = { message ->
/* Handle message */
}
subscription.onSignal = { signal ->
/* Handle signal */
}
subscription.onMessageAction = { messageAction ->
/* Handle message action */
}
subscription.onFile = { file ->
/* Handle file event */
}
show all 23 linesThe following is an overview of each of the event listeners. Details about the data passed to the handlers' parameters will be explained in the API sections of the associated handlers.
Subscription with Presence
To receive Presence events, you subscribe with Presence and have Presence enabled on your keyset. Make sure you configure Presence to track Presence-related events for all or selected channels (through Presence Management rules).
Handler | Description |
---|---|
Status | Receives events when the client connects (subscribes) or reconnects to channels. For other error events the Status handler can receive, see Connection Management and the tip that follows this table. In entity-enabled SDKs, add this listener to the pubnub object, not to an individual subscription. |
Message | Receives all messages published to channels the client subscribes to. The event payload contains the published message data, publish timetoken, the user ID of the publisher, and more. See Publish Messages. |
Signal | Receives all signals sent to any subscribed channels. The event payload contains the signal data, signal timetoken, the user ID of the publisher, and more. See Send Signals. |
Presence | Receives presence events on subscribed channels. Event types include join , leave , timeout , and state-change . The payload includes a timetoken for the action, the user ID, and optional state data. See Detect Presence. |
MessageAction | Receives events when messages are annotated by an action on any subscribed channels. The payload includes the user ID that acted, action type (such as an emoji reaction), timetoken of the annotated message, timetoken of the action, action value, and more. See Message Actions. |
Objects | Receives objects events when channel, membership, or user metadata is created, updated, or removed. See App Context. |
Status event handling
PubNub automatically tries to reconnect after transient network issues. For more about status events and troubleshooting, see SDK troubleshooting and status event references.