Receive Messages
To receive a message, your client must implement a listener and subscribe to a channel in which the message is being published.
Add a Listener
Messages and events are received in your app using a listener. This listener allows a single point to receive all messages, signals, and events.
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.
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
- Android
- C#
- Go
- Python
- Dart
pubnub.addListener({
message: function(m) {
// handle message
var channelName = m.channel; // The channel to which the message was published
var channelGroup = m.subscription; // The channel group or wildcard subscription match (if exists)
var pubTT = m.timetoken; // Publish timetoken
var msg = m.message; // The Payload
var publisher = m.publisher; //The Publisher
},
presence: function(p) {
// handle presence
var action = p.action; // Can be join, leave, state-change, or timeout
var channelName = p.channel; // The channel to which the message was published
var occupancy = p.occupancy; // Number of users subscribed to the channel
var state = p.state; // User State
show all 67 lines// 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")")
case let .connectionStatusChanged(status):
print("Status Received: \(status)")
case let .presenceChanged(presence):
print("Presence Received: \(presence)")
case let .subscribeError(error):
print("Subscription Error \(error)")
default:
show all 21 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 107 lines// 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() {
// PubNub status
@Override
public void status(PubNub pubnub, PNStatus status) {
switch (status.getOperation()) {
// combine unsubscribe and subscribe handling for ease of use
case PNSubscribeOperation:
case PNUnsubscribeOperation:
// Note: subscribe statuses never have traditional errors,
// just categories to represent different issues or successes
show all 135 linespubnub.AddListener(new SubscribeCallbackExt(
// Messages
delegate (Pubnub pnObj, PNMessageResult<object> pubMsg)
{
Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(pubMsg));
var channelName = pubMsg.Channel;
var channelGroupName = pubMsg.Subscription;
var pubTT = pubMsg.Timetoken;
var msg = pubMsg.Message;
var publisher = pubMsg.Publisher;
},
// Presence
delegate (Pubnub pnObj, PNPresenceEventResult presenceEvnt)
{
Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(presenceEvnt));
show all 80 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# The Python SDK doesn't currently support *Server App Context*,
# so it doesn't have any handlers for them.
class SubscribeHandler(SubscribeCallback):
def status(self, pubnub, event):
print("Is there an error? ", event.is_error()) # Method showing error or not
print("Status value for category: %s" % event.category)
print("Status value for error_data: %s" % event.error_data)
print("Status value for error: %s" % event.error)
print("Status value for status_code: %s" % event.status_code)
print("Status value for operation: %s" % event.operation)
print("Status value for tls_enabled: %s" % event.tls_enabled)
print("Status value for uuid: %s" % event.uuid)
print("Status value for auth_key: %s" % event.auth_key)
print("Status value for origin: %s" % event.origin)
show all 30 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 linesThe following is an overview of each of the listener's event handlers. Details about the data passed to the handlers' parameters will be explained in the API sections of the associated handlers.
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. |
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 action 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 Channel Metadata, User Metadata, and Membership Metadata. |
Status event handling
For more information on how the SDKs handle status events, refer to SDK troubleshooting and status event references.