Receive messages
Receiving messages (or any other events for that matter) is a three-step process:
- Create a subscription or a subscription set.
- Implement the appropriate event listener.
- Subscribe to the subscription to start receiving real-time updates.
PubNub SDKs make the entire process easy by introducing objects we call entitiesEntity
A subscribable object within a PubNub SDK that allows you to perform context-specific operations.Channel
works on channels, UserMetadata
works on user metadata objects, and so on. There are four entities you can use:
Channel
ChannelGroup
UserMetadata
ChannelMetadata
Entity-enabled SDKs
Not all PubNub SDKs currently support entities. Refer to each SDK's API documentation for more information.
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.
- JavaScript
- Swift
- Objective-C
- Java
- C#
- Python
- Dart
- Kotlin
// create a subscription to a single channel
const channel = pubnub.channel('chats_inbox.user_1905')
const subscription1 = channel.subscription({ receivePresenceEvents: true });
// create a subscription to multiple channels
const channels = pubnub.subscriptionSet({
channels: [
"chats_guilds.mages_guild",
"alerts.system",
"geolocation.data"
]
});
const subscription2 = channels.subscription();
// subscribe to both subscriptions and
show all 18 lines// create a subscription to a single channel
let subscription1 = pubnub.channel("chats_inbox.user_1905").subscription()
// create a subscription to the channel, channel group, and
// user metadata updates
let subscriptionSet = pubnub.subscription(
entities: [
pubnub.channel("chats_guilds.mages_guild"),
pubnub.channelGroup("alerts.system"),
pubnub.userMetadata("user_1905_md")
],
options: ReceivePresenceEvents()
)
// subscribe to both subscriptions and
show all 18 lines[self.pubnub subscribeToChannels: @[@"chats_guilds.mages_guild", @"alerts.system", @"geolocation.data"] withPresence:NO];
// Step 1: Create a subscription set
SubscriptionSet subscriptionSet = pubnub.subscriptionSetOf(
Set.of("chats_guilds.mages_guild", "alerts.system", "geolocation.data"),
Collections.emptySet(),
EmptyOptions.INSTANCE);
// Step 2: Subscribe using the subscription set
subscriptionSet.subscribe();
SubscriptionSet subscriptionSet = pubnub.Subscription(
new string[] {"chats_guilds.mages_guild", "alerts.system", "geolocation.data"}},
SubscriptionOptions.ReceivePresenceEvents
)
subscriptionSet.Subscribe<object>()
channel1 = pubnub.channel("channelName")
channel2 = pubnub.channel("channelName2")
subscription_set1 = pubnub.subscription_set([channel, channel2])
subscription_set1.subscribe()
var subscription = pubnub.subscribe(channels: {'chats_guilds.mages_guild', 'alerts.system', 'geolocation.data'});
// create a subscription to a single channel
val myChannel = pubnub.channel("chats_inbox.user_1905")
val subscription = myChannel.subscription()
// create a subscription to multiple channels
val subscriptionSet = pubnub.subscriptionSetOf(
// Specify channels with default options
channels = setOf("chats_guilds.mages_guild","alerts.system","geolocation.data")
)
// subscribe to both subscriptions and
// start receiving real-time updates
subscription.subscribe()
subscriptionSet.subscribe()
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.
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.
Add listeners to subscriptions and subscription sets for specific or multiple subscriptions simultaneously.
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.
Every received message has an internal message type (an immutable integer) and custom message type (a mutable string that you can set to whatever you wish) parameters which allow you to easily filter, group, or apply conditional logic to different types of messages. The code below prints out all messages.
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#
- Python
- Dart
- Kotlin
// add a subscription connection status listener
pubnub.addListener({
status: (s) => {console.log('Status', s.category) }
});
// add message and presence listeners
subscription.addListener({
// Messages
message: (m) => { console.log('Received message', m) },
// Presence
presence: (p) => { console.log('Presence event', p) },
});
// add a subscription connection status listener
pubnub.onConnectionStateChange = { newStatus in
print("Connection Status: \(newStatus)")
}
// add message listener
subscription.onEvent = { event in
switch event {
case let .messageReceived(message):
print("Message Received: \(message) Publisher: \(message.publisher ?? "defaultUUID")")
default:
break
}
}
// 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 {
id msg = message.data.message; // Message payload
NSString *publisher = message.data.publisher; // Message publisher
}
pubnub.addListener(new EventListener() {
// Messages
@Override
public void message(PubNub pubnub, PNMessageResult message) {
String messagePublisher = message.getPublisher();
System.out.println("Message publisher: " + messagePublisher);
System.out.println("Message Payload: " + message.getMessage());
}
});
Subscription subscription1 = pubnub.Channel("channelName").Subscription()
subscription1.OnMessage = (Pubnub pn, PNMessageResult<object> messageEvent) => {
Console.WriteLine($"Message received {messageEvent.Message}");
};
subscription1.Subscribe<object>()
subscription = pubnub.channel(f'{channel1}').subscription()
def on_message(listener):
def message_callback(message):
print(f"\033[94mMessage received on: {listener}: \n{message.message}\033[0m\n")
return message_callback
def on_message_action(message_action):
print(f"\033[5mMessageAction received: \n{message_action.value}\033[0m\n")
subscription.on_message = on_message('message_listener')
subscription.on_message_action = on_message_action
subscription.subscribe()
subscription.messages.listen((envelope) {
switch (envelope.messageType) {
case MessageType.normal:
print('User with id ${envelope.uuid} sent a message: ${envelope.content}');
break;
default:
print('User with id ${envelope.uuid} sent a message: ${envelope.content}');
}
});
// add the subscribe connection status listener
pubnub.addListener(object : StatusListener() {
override fun status(pubnub: PubNub, status: PNStatus) {
// This block is executed asynchronously for each status update
println("Connection Status: ${status.category}")
}
})
// add the message and signal listeners
subscription.addListener(object : EventListener {
override fun message(pubnub: PubNub, message: PNMessageResult) {
// Log or process message
println("Message: ${message.message}")
}
show all 20 linesYou 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.