Presence lets you track the online and offline status of users and devices in real time and store custom state information. When you have Presence enabled, PubNub automatically creates a presence channel for each channel. Subscribing to a presence channel or presence channel group returns only presence events.
For more details on working with presence, refer to the Presence Tutorial.
Get online users in a channel
hereNow() method to get information about the current state of a channel, including a list of unique users currently subscribed to the channel.
PubNub triggers presence events as users come online or go offline from the application. Clients can receive these events directly, or you can use webhooks on a server to keep a user's online/offline status up to date. Use these events to keep track of users coming and going, as well as total occupancy of the channel.
|Fires when a user subscribes to a channel.|
|Fires when a user unsubscribes from a channel.|
|Fires when a connection to a channel is lost and the subscriber hasn't been seen in 320 seconds (just over 5 minutes).|
|Fires anytime the user's state is changed using the state API (function signature varies by SDK).|
|Fires to provide an occupancy count. The default setting for the Presence Interval property is 10 seconds, which is configurable on your PubNub Dashboard's Presence add-on panel.|
Add Presence Listeners
To receive presence events in a client, add presence event listeners from the SDK.
Subscribe to Presence Channels
Once you've added presence listeners, call
subscribe() with the
withPresence flag enabled to receive presence events. You can also directly subscribe to presence channels by adding
-pnpres to the original channel name.
Use presence webhooks
Use presence webhooks to have PubNub notify your server whenever presence events occur on any channel for your keys. This provides a scalable solution for your server-side application to monitor presence events.
Before you implement the REST endpoints, it's helpful to know what the events' data looks like. Here is an example of a
The JSON payload is the same for
state-change, other than the value of the
action object. You would only include the
data object if there was state data involved, but this is everything you need to consider. The content-type for these events is
If a channel has no subscribers, its status changes from
inactive. For these channel-level state changes, the content-type is
The value of
status can be either
Once your server's REST endpoints are implemented and the PubNub key configuration is in place, you're ready to go.
You may find it useful to provide separate endpoints for active/inactive and join/leave/timeout/state-change events, but there is no requirement to do so.