Getting started with PubNub

By | 08/12/2014

[keen]

Inspired by this blogpost from my good friend Antonio Mancuso, I decided to experiment also a little bit with PubSub. I know the technology from previous experiences but I have never been able to really take a deep dive into it. As Antonio gave an example based on Ruby, I decided to create an equivalent using Python. Just for fun of course! I believe the below picture from PubNub really explains it very nice. We will implement the ‘broadcast’ variant:

pubnub

In below snippet, we create the publisher, which is the entity that is pushing messages to the subscribers that are listening to it. Obviously, I’m assuming you have created an account on http://www.pubnub.com.

import datetime
from Pubnub import Pubnub

publish_key = ''
subscribe_key = ''
channel = 'wapptastic'
message = 'Hello Wapptastic'

pubnub = Pubnub(publish_key=publish_key, subscribe_key=subscribe_key)

def callback(message):
   
    print(message)

pubnub.publish(channel, message, callback=callback, error=callback)

Below we create a subsriber which listens to the channel used by the publisher:

import datetime
from Pubnub import Pubnub


publish_key = ''
subscribe_key = ''
channel = 'wapptastic'

pubnub = Pubnub(publish_key=publish_key, subscribe_key=subscribe_key)

def callback(message, channel):
    print(message)


def error(message):
    print("ERROR : " + str(message))


def connect(message):
    print("CONNECTED")


def reconnect(message):
    print("RECONNECTED")


def disconnect(message):
    print("DISCONNECTED")


pubnub.subscribe(channel, callback=callback, error=callback,
                 connect=connect, reconnect=reconnect, disconnect=disconnect)

The results can be seen in below screenshot. Pretty neat service I have to admit.

Screenshot from 2014-11-26 17:48:46