Presence Getting Started Guide
Demo URL:
http://pubnub.github.io/apiguidewithtictactoe/presence.html Presence In a Nutshell
PubNub provides
presence
and
state
functionality which is built upon the publish & subscribe foundation making it easy to answer the question
who’s online, and what are they doing?
And being a global data stream network, PubNub will enable you to know when people come and go without repeated requests. The
state
provides data like name, age, online status (available, busy, typing, geolocation, etc.) enabling you to create rich user experience applications that leverage the actual participants of your application. Presence Use Cases
●
●
●
●
●
Chat rooms: Showing users’ online status Collaborative Word doc: Showing who is typing Smart sensors: Showing how many devices are connected Multiplayer gamings: Showing all players names and stats Interactive media: audienceparticipating voting system Chat App Scenarios
●
●
●
●
Notifying when a user has joined or left a channel Displaying who, and how many, users are subscribed to a particular channel Showing which channel(s) an individual user is subscribed to Showing associated state information for these users (location, typing status, etc) Setting up Presence Add-on
To use the addon feature, you need to enable
Presence
for your key in the
Admin Dashboard
. You can choose additional configuration values at the configuration modal dialog. You can always come back to your admin dashboard to modify the settings later. Using Presence API
Before proceeding, be sure you have completed the Pub & Sub tutorial first. Demo
You can take a look at the
Tic Tac Toe demo
for Presence
that explains how the APIs work, along with this documentation. Default Presence Events
There are 3 types of default online status events that the Presence API listens to and publishes: ● Join when a user or device subscribes to the channel ● Leave when a user or device unsubscribes from the channel ●
Timeout when PubNub does not hear back from the device after a specified duration First, you need to initialize your connection to PubNub with a Unique User ID (UUID): varpubnub
=PUBNUB
({
publish_key
:
'your_pub_key',
subscribe_key
:
'your_sub_key',
uuid
:
'user-1234'
});
Once a UUID is set, you can enable presence events along with the subscribe call. You can also retrieve several event messages at the presence callback: pubnub
.
subscribe
({
channel
:
'
tic
-
tac
-
toe
',
presence
:
function
(
m
){
console
.
log
(
m.action
) // online status events
console
.
log
(
m.timestamp
) // timestamp on the event is occurred
console
.
log
(
m.uuid
) // uuid of the user
console
.
log
(
m.occupancy
) // current number of users online
},
...
});
Examples
Let’s see
how the presence works on the TicTacToe demo
. Notice the number of players is displayed at the left hand side of the Tic Tac Toe board. Additionally, when you don’t have an another player, you get the message, “Waiting for your opponent…” at the right hand side. If more than two people are joining to the same game, whoever joined after the 2nd player gets an alert message so they cannot play the game. This feature is done by using the Presence API. At the
Presence API Explained
section of the demo, you can liveview the “console” as a new event is triggered. Watch it while trying to join into the game from an another browser window or a tab, then kill the browser window/tab to trigger the timeout event. You can also manually “leave” by unsubscribing from the game. (See the Quit button on the demo page). State-change Event
Additionally, there is an another status event:
state-change
● statechange when a custom value is modified You can define custom state attributes, which can be any arbitrary data object. The statechange event is triggered when any of the values are modified. For example, let’s say you are developing a chat app, and when you define the custom data to track if a user is currently typing: {
isTyping
:
false}
The value changes to
true
as soon as the user starts pressing any alphanumeric keys.
You can set the state, using
state
method: pubnub
.
state
({
channel
:
"awesome-chat",
uuid
:
"user-1234",
state:{
isTyping
:
true
},
callback
:
function
(
m
){
...
}
});
When the data change is detected,
state-change
event is fired at the presence callback with subscribe: pubnub
.
subscribe
({
channel
:
'
awesome-chat
',
presence
:
function
(
m
){
if
(
m
.
action
===
'state-change'
){
if
(
m
.
data
.
isTyping
===
true
){
dom
.
textContent
=m
.
uuid
+
' is typing...';
}
}
},
...
}); Non-Streaming Event
While Presence events like
join
and
leave
are received via longrunning listener processes, some data can be retrieved on request when required in a shortlived request/response cycle. For example, you may need to know who is subscribed to a channel
right now.
● Here Now Gets a list of subscribers for a given channel ● Where Now Gets a list of channels that a given client is subscribed to ● Global Here Now Gets a list of every subscriber (by UUID) on every active channel associated with your keys. ● Get State Get the user state metadata that a given client is subscribed to To get a list of "who is here now" for a given channel, use the
here_now()
method: pubnub
.
here_now
({
channel
:
'awesome-chat',
callback
:
function
(
m
){
console
.
log
(
m
)}
});
To get a list of "which channel(s) is this UUID on right now", use the
where_now()
method: pubnub
.
where_now
({
channel
:
'awesome-chat',
uuid:
'user-666',
callback
:
function
(
m
){
console
.
log
(
m
)}
});
Optimizing Timeout Events
Timeout events are triggered when the server does not hear a heartbeat from the client within a default timeout time of 280 seconds. This default timeout time can be adjusted, as well as the frequency in which the client sends heartbeats to the server. You can configure them at initialization: varpubnub
=PUBNUB
.
init
({
});
publish_key
:
'your_pub_key',
subscribe_key
:
'your_sub_key',
uuid
:
'user-3456',
heartbeat
:
120
By default, the
heartbeat interval
is set heartbeat/2 1. When you manually set the heartbeat to 120 seconds, the client will send a heartbeat “ping” every 59 (= 120 / 2 1) seconds. Also, you can override the heartbeat interval if you wish: varpubnub
=PUBNUB
.
init
({
publish_key
:
'your_pub_key',
subscribe_key
:
'your_sub_key',
uuid
:
'user-3456',
heartbeat
:
120,
heartbeat_interval
:
30 // the frequency of ping from client to server
});
In the above example, the server knows to emit a timeout event if it does not receive a ping from it within 120s. The device will ping back from the client to the server to tell it is alive every 30s. You should be careful with the network connection types and conditions. Also keep in mind more frequent ping means more battery consumption, especially on mobile devices.
© Copyright 2026 Paperzz