Question

I'm creating a person-to-person chat app using PubNub.

Basically, each user is subscribed to their own channel, and then messages are sent by the two parties to each other's channel in an Instant messaging fashion.

The messages are then displayed on the page. I'm using JQuery for this.

pubnub.subscribe({
    restore  : true,
    channel  : 'my_channel',
    callback : function(message) {
        console.log(JSON.stringify(message));
        $('div.chatbox').append('<div>'+message+'</div>');
    }
});

However, I want to be able to detect when a user has gone offline (I don't really care how they went offline just that the connection to the other party is no longer available).

So if User 1 and User 2 are in conversation, then User 2 goes offline, is there any mechanism on the PubNub side that allows User 1 to check the connection status of User 2? How would I implement this in JS code (skeleton code is ok)?

Thanks in advance.

P.S. I don't want to use Socket.IO

Was it helpful?

Solution

How to Detect Dropped Friend's & Self (Local) Network Connections with PubNub

In order to detect dropped network connections on mobile, tablet and web devices you can use PubNub to show connection state by binding to built-in events in the PubNub JavaScript API. There are several aspects to understanding dropped connection and reconnection states. Also with PubNub you may be interested in social discovery of connection/disconnection events of your online friends. This way you can have the green dot effect which indicates your friends online state and a red dot when your friend is offline. We'll go over two sides to connectivity state tracking so you will be able to detect and notify your users when their own device goes offline/online and also when their friends go online/offline.

Detecting Local Connection State with JavaScript PubNub API

It is simple to detect your local connection state to the internet on any JavaScript ready devices such as mobile phones and web browsers. You will use a little bit of advanced PubNub paramaters to give you access to the callbacks that get fired during connection state changes. It is easy to register for the callbacks in your application code. Here is a quick copy/paste starting point for you to keep in your back pocket:

<div pub-key="demo" sub-key="demo" id="pubnub"></div>
<script src="http://cdn.pubnub.com/pubnub-3.3.min.js"></script>
<script>(function(){

// LISTEN FOR MESSAGES
PUBNUB.subscribe({
    channel    : "hello_world",      // CONNECT TO THIS CHANNEL.
    restore    : true,               // STAY CONNECTED, EVEN WHEN BROWSER IS
                                     // CLOSED OR WHEN PAGE CHANGES.
    callback   : alert,              // FUNCTION TO RUN ON MESSAGE RECEIVED.

    disconnect : function() {        // LOCAL LOST CONNECTION.
        alert("Connection Lost.")
    },
    reconnect  : function() {        // CONNECTION RESTORED.
        alert("And we're Back!")
    },
    connect    : function() {        // CONNECTION ESTABLISHED.
        PUBNUB.publish({             // SEND A MESSAGE.
            channel : "hello_world",
            message : "Hi from PubNub."
        }) 
    }
})

})();</script>

NOTE: Shown above is a simple method for registering for local device connectivity events.

Now time to talk about PubNub Presence; a feature of PubNub which allows you to detect your friend's connections and receive remote connectivity events when your friends go online or offline.

Detecting Friends Online/Offline States with PubNub Presence

Next you want to learn about detecting your friends connectivity states as they come online and also go offline. You can register for these events too, though it will be a little more work on your side as you need to provide the ID (or abstract ID) of your users. You can do this with PubNub presence however it is a bit more involved and I will send you to two blog posts that will get you going quickly. Before I send you off, I will show you the important code snippets for registering for remote online/offline event notifications from your friends:

// Open Bidirectional Socket Connection with
// REMOTE Connection Detect "Presence" Events.
PUBNUB.subscribe({
    channel  : "my_channel", // Channel Name
    connect  : connect,      // OnConnect Callback
    callback : alert,        // Received Message Callback
    presence : presence      // Presence Callback
});

NOTE: Receive Remote Connection Status Updates (Friends Connection States) with the PubNub Presence Callback Event.

In the code sample you will see a presence callback. This paramater option requires a function reference which will be executed when connection changes occur (online/offline) of your friends on the same PubNub Channel. Okay now that you got the gist of things, you need to check out the following blog posts to help you with specific details about PubNub presence.

PubNub Presence Resources

Use the above links and references to learn all you need to know about PubNub Presence

OTHER TIPS

See also the Channel Presence FAQ at help.pubnub.com knowledge base.

Using socket.io for presence functionality is limited to the client side (often, your server will also need to obtain presence info to manage client interactions or conversations) and is a very chatty protocol that leads to excessive battery drain and data plan waste on mobile phone.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top