Receive Messages
Messages sent through PubNub are no different from any other PubNub event. They are only structured differently.
Receiving messages (or any other events for that matter) is a three-step process:
- Create an entity-based subscription or a subscription set.
Entity
A subscribable object within a PubNub SDK that allows you to perform context-specific operations. - Implement the appropriate event listener.
- Subscribe to the subscription to start receiving real-time updates.
Entity-enabled SDKs
Not all PubNub SDKs currently support entities. For the SDKs that still use the legacy event listeners and Subscribe API, the information about the API remains in their respective SDK API docs.
Refer to each SDK's API documentation for more information.
Add an event handler
Messages and events are received in your app using event handlers (also called listeners). In those listeners, you add the logic for handling all received messages, signals, files, and events.
Add listeners to subscriptions and subscription sets for specific or multiple subscriptions simultaneously.
There are four entities:
Each type of message or event has its own handler to receive them where you implement your custom app logic to do something useful with the received data.
Subscription with Presence
You must create a subscription with Presence enabled to receive Presence events. For more information, refer to each SDK's Publish and Subscribe documentation.
Once you no longer need to handle events in your app, you can remove a listener using a corresponding SDK method. See Javascript SDK as an example.
The following handlers are available to you:
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 reaction */
}
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
You must create a subscription with Presence enabled to receive Presence events. For more information, refer to each SDK's Publish and Subscribe documentation.
Handler | Description |
---|---|
Status | Receives events when the client successfully connects (subscribes), or reconnects (in case of connection issues) to channels. For other error events that can be received by the Status handler, refer to Connection Management and to the tip that follows this table. In entity-enabled SDKs, you can only add this listener to the pubnub object, not to an individual subscription. |
Message | Receives all messages published to all the channels subscribed by the client. The event payload will contain the published message data, publish timetoken, the User ID of the client that published the message and more. Refer to Publish Messages. |
Signal | Receives all signals that are sent to any channels subscribed by the client. The event payload will contain the signal data, signal timetoken, the User ID of the client that published the message and more. Refer to Send Signals. |
Presence | Receives all presence events that are triggered on any channels subscribed by the client. The event payload will contain the presence event type (join , leave , timeout , state-change ), timetoken of the action, the User ID of the client that caused the event, state data (if applicable) and more. Refer to Detect Presence. |
MessageAction | Receives all events when existing messages are annotated (by an action) for any channels subscribed by the client. The event payload will contain the User ID that acted on the message, message reaction type (such as an emoji reaction), timetoken of the annotated message, timetoken of the action, action value and more. Refer to Message Reactions. |
Objects | Receives all objects events that are emitted when a channel, channel membership, or user metadata is created, updated or removed. Refer to App Context. |
Status event handling
For more information on how the SDKs handle status events, refer to SDK troubleshooting and status event references.