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.
- JavaScript
- Swift
- Objective-C
- Android
- C#
- Python
- Dart
- Kotlin
// 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"
]
});
pubnub.subscribe(to: ["chats_guilds.mages_guild", "alerts.system", "geolocation.data"])
[self.pubnub subscribeToChannels: @[@"chats_guilds.mages_guild", @"alerts.system", @"geolocation.data"] withPresence:NO];
pubnub.subscribe().channels(Arrays.asList("chats_guilds.mages_guild", "alerts.system", "geolocation.data"));
pubnub.Subscribe<string>()
.Channels(new string[] {"chats_guilds.mages_guild", "alerts.system", "geolocation.data"})
.Execute();
pubnub.subscribe()\
.channels("chats_guilds.mages_guild", "alerts.system", "geolocation.data")\
.execute()
var subscription = pubnub.subscribe(channels: {'chats_guilds.mages_guild', 'alerts.system', 'geolocation.data'});
pubnub.subscribe(
channels = listOf("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.
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
- Android
- C#
- Python
- Dart
- Kotlin
pubnub.addListener({
message: function(receivedMessage) {
// handle message
console.log("The message text is: ", receivedMessage.message);
console.log("Sent by: ", receivedMessage.publisher);
}
});
// Create a new listener instance
let listener = SubscriptionListener()
// Add listener event callbacks
listener.didReceiveSubscription = { event in
switch event {
case let .messageReceived(message):
print("Message Received: \(message) Publisher: \(message.publisher ?? "defaultUUID")")
default:
break
}
}
// Start receiving subscription events
pubnub.add(listener)
// 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
}
// SubscribeCallback is an Abstract Java class. It requires that you
// implement all Abstract methods of the parent class even if you don't
// need all the handler methods.
pubnub.addListener(new SubscribeCallback() {
// 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());
}
});
pubnub.AddListener(new SubscribeCallbackExt(
// Messages
delegate (Pubnub pnObj, PNMessageResult<object> pubMsg)
{
Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(pubMsg));
var msg = pubMsg.Message;
var publisher = pubMsg.Publisher;
}
));
# The Python SDK doesn't currently support *Server App Context*,
# so it doesn't have any handlers for them.
from pubnub.callbacks import SubscribeCallback
class SubscribeHandler(SubscribeCallback):
def message(self, pubnub, message):
print("Message payload: %s" % message.message)
print("Message publisher: %s" % message.publisher)
pubnub.add_listener(SubscribeHandler())
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}');
}
});
pubnub.addListener(object : SubscribeCallback() {
override fun message(pubnub: PubNub, message: PNMessageResult) {
val messagePublisher: String? = message.publisher
println("Message publisher: $messagePublisher")
println("Message Payload: " + message.message)
}
})
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.