Pages

2012-02-04

A PubNub Stub

Stumbled across PubNub at work the other day.  Neat stuff.  Really easy to create distributed web apps.  Observe:

<html>
<body>
<div id="out">Click subscribe to subscribe to the messages sent by the "Send message" button.</div>
<form>
<button onclick="subscribe(); return false;">Subscribe</button>
<button onclick="sendMessage(); return false;">Send message</button>
</form>

<div pub-key="demo" sub-key="demo" ssl="off" origin="pubsub.pubnub.com" id="pubnub"></div>
<script src="http://cdn.pubnub.com/pubnub-3.1.min.js"></script>
<script src="demo.js"></script>
</body>
</html>
And the javascript:
function subscribe() {
    PUBNUB.subscribe({
        channel     :   "test",
        error       :   function() { alert("Connection lost.  Will auto-reconnect when Online."); },
        callback    :   function(msg) { PUBNUB.$("out").innerHTML = msg; },
        connect     :   function() { alert("Connected!"); }
    });
}
var i = 0;
function sendMessage() {
    PUBNUB.publish({
        channel     :   "test",
        message     :   "You've clicked the button "+i+" time"(i==1?"":"s")+"!"
    }); 
    i = i + 1;
}
Let's break it down a bit:

The HTML's pretty straightforward.  A div that we'll alter with the innerHTML property, and a couple buttons tied to the subscribe and sendMessage functions, respectively.  (We could just as easily subscribe on page load.)

The javascript is the interesting bit.  There are really only two PubNub API calls you need to know:  subscribe and publish.  Both functions take an object requiring a few simple properties.

Subscribe:

  • channel - Any name you like.  You subscribe to a channel, and any messages published to that channel are received as the argument to the function attached to the callback property.
  • error - A callback for when errors occur.
  • callback - The function that gets called when a message is published to that subscribed-to channel
  • connect - A callback that notifies you when the connection to PubNub has been established
Publish:
  • channel - The name of the channel to publish to
  • message - The message to send
Simple as that!  You'll note that they've even provided jQuery-like access to the DOM, so you can do things like
PUBNUB.$("out").innerHTML = msg.

You can get publisher and subscriber keys that you put in the pub-key and sub-key attributes of the pubnub div by going to pubnub.com.  Go ahead and try loading the code above in a couple browsers.  In a couple browsers on different machines, even, and enjoy the simplicity of distributed communication with PubNub!


No comments:

Post a Comment