Erlang PubNub Client and Chat
I was thoroughly impressed with PubNub, a publish/subscribe service, when I first read their articles and played around with it some in Javascript. But obviously I need an Erlang API if I’m going to really use it! So I’ve created ePubNub.
In the ePubNub README you’ll find information on some basic usage of the application. You don’t have to do anything more than use the epubnub.erl module to publish and subscribe (by either providing a PID to send messages to or a function handler to process each).
Here I’ve built a little more complicated app/release called epubnub_chat, and the source is also on github.
The first thing we need is the epubnub app as a dependency in the epubnub_chat.app file:
We’ll use a simple_one_for_one for supervising channel subscribed processes. In e_pubnub_chat_sup_ we have 3 API functions for the user to use (_start_link_ is run by the __app.erl_ module on startup): _connect/1_, _connect/2_, _disconnect/1_:
EPN is a record containing the necessary url and keys for talking to the PubNub service and is created with the new functions in epubnub:
You can pass none to connect/1 and it will send none to the chat gen_server and it will use defaults of pubsub.pubnub.com, demo and demo, for the url, publish key and subscribe key respectively.
Now in the epubnub_chat gen_server we need the following API functions:
The start_link functions are run when the supervisor spawns a simple_one_for_one supervisor for the process. This returns {ok, PID}. This PID must be remembered so we can talk to the process we have started thats subscribed to a specific channel. We pass this PID to the message/2 and stop/1 functions, which we’ll see at the and when we use the program.
start_link/1 and /2 call init/1 with the provided arguments:
Here we use the epubnub_sup subscribe/3 function and not epubnub:subscribe because we want it to be supervised. We store the PID for this process so we can terminate it later.
The epubnub subscribe process was given the PID, returned by self/1, of the current process which is the gen_server process and will send messages that are published to the channel to that process. We handle these messages in handle_info/2:
Lastly, we have to handle the messages from message/2 and stop/1:
The handle_cast/2 function published your message to the channel this process subscribed to with epubnub:publish/3 and terminate calls epubnub:unsubscribe/1 before this process ending which sends a terminate message to the subscibred process.
Now lets see this program in action:
You can go to the PubNub tutorial page to chat between yourself, or get someone else to join!
That’s it! Simple and quick global communication that scales for you!
I’ve really enjoyed playing with PubNub and hope I get to use it for a real project soon.