Setup and event listeners
All chat applications have a notion of a user. It's important to be able to uniquely identify users as they interact with the PubNub Network. Usually, a user is a human end user—a person using an app to interact with a system (via a laptop, phone, tablet, or kiosk).
You use a User ID to uniquely identify each user on the system. Users can connect from multiple devices, such as phones, tablets, desktops, etc., using the same User ID. If a user is connected from multiple devices simultaneously, they will receive the same messages on each device.
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.
Setup
Start by initializing a PubNub object with publishKey
, subscribeKey
, and userId
as required fields. The userId
is a string of maximum 92 characters that represents a user in your application.
Your publish and subscribe keys are available in your PubNub Account. Go to the Admin Portal to create your free account.
userId is required
Setting the userId
parameter is required to establish a connection to PubNub, ensure that your billing is accurate, and for other features like presence and storage to work as expected.
- JavaScript
- Java
- Swift
- Objective-C
const pubnub = new PubNub({
subscribeKey: "mySubscribeKey",
publishKey: "myPublishKey",
userId: "john-doe",
autoNetworkDetection: true, // enable for non-browser environment automatic reconnection
restore: true, // enable catchup on missed messages
});
PNConfiguration.Builder configBuilder = PNConfiguration.builder(new UserId("yourUserId"), "yourSubscribeKey");
configBuilder.publishKey("myPublishKey");
PubNub pubNub = PubNub.create(configBuilder.build());
let config = PubNubConfiguration(
publishKey: "myPublishKey",
subscribeKey: "mySubscribeKey",
userId: "john-doe"
)
let pubnub = PubNub(configuration: config)
PNConfiguration *pnconfig = [PNConfiguration configurationWithPublishKey:@"myPublishKey"
subscribeKey:@"mySubscribeKey"];
pnconfig.uuid = "john-doe";
self.pubnub = [PubNub clientWithConfiguration:pnconfig];
Add event listeners
Events are received in your app using listeners. These listeners allows a single point to receive messages, signals, and presence events. Each event type has its own handler to receive them where you implement your custom app logic to perform actions on events.
The following handlers are available to you:
Handler | Description |
---|---|
Status | Receives events when the client successfully connects (subscribes), or reconnects (in case of connection issues) to channels. |
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. |
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. |
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. |
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. |
Objects | Receives all objects events that are emitted when a channel, channel membership, or user metadata is created, updated or removed. |
- JavaScript
- Java
- Swift
- Objective-C
- Unity
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 linespubnub.addListener(new StatusListener() {
// PubNub status
@Override
public void status(PubNub pubnub, PNStatus status) {
switch (status.getCategory()) {
/* handle various statuses */
}
}
});
pubnub.addListener(new EventListener() {
// Messages
@Override
public void message(PubNub pubnub, PNMessageResult message) {
String messagePublisher = message.getPublisher();
show all 90 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 ?? "defaultUserID")")
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 106 linespubnub.SubscribeCallback += SubscribeCallbackHandler;
//Handler
void SubscribeCallbackHandler(object sender, EventArgs e) {
SubscribeEventEventArgs mea = e as SubscribeEventEventArgs;
if (mea.Status != null) {
switch (mea.Status.Category) {
case PNStatusCategory.PNUnexpectedDisconnectCategory:
case PNStatusCategory.PNTimeoutCategory:
pubnub.Publish()
.Channel("my_channel")
.Message("Hello from the PubNub Unity SDK")
.Async((result, status) => {
if(!status.Error){
show all 70 lines