Universal Messaging 10.5 | Developer Guide | Web Client APIs | Web Developer's Guide for Javascript | Example: Implementing a Simple Pub/Sub Client
 
Example: Implementing a Simple Pub/Sub Client
The Universal Messaging JavaScript API makes it easy to implement JavaScript Publish & Subscribe clients. These clients can communicate using Comet techniques (both streaming and long-polling), as well as using Web Sockets when supported by the client browser.
The code shown below is a fully functioning example of such a client, containing JavaScript connection, publishing and subscription logic and an HTML UI.
In some circumstances you may wish to serve your web application from another web server (e.g. Apache). Universal Messaging supports this also but due to security restrictions within browsers it requires that your application is organised differently (see Serving From Another Webserver for related information).
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>Page Title</title>

<script language="JavaScript" src="lib/nirvana.js"></script>

<script>

// this needs to be configured based on the server host you are executing this example against
var hostName = "http://localhost:11000";
// this needs to be configured based on the channel name
var channelName = "/showcase/simplechatroom";

var demoUsername = "anonymous";

/********************************************************************
* As soon as the page loads, we should create our Universal Messaging session.
* We use the object Nirvana and define what
* we want to happen once the session is initialised by implementing
* a callback function, NirvanaSession.onInit:
*********************************************************************/

var session = Nirvana.createSession({
realms : [ hostName ],
// this can be an array of realms
debugLevel : 4, // 1-9 (1 = noisy, 8 = severe, 9 = default = off)
sessionTimeoutMs : 10000,
enableDataStreams : false,
drivers : [ // an array of transport drivers in preferred order:
Nirvana.WEBSOCKET,
Nirvana.XHR_STREAMING_CORS,
Nirvana.XDR_STREAMING,
Nirvana.JSONP_LONGPOLL
]
});

session.start();

function isLoaded() {

/********************************************************************
* Now that our session has initialised, we can access an automatically
* instatiated object named Nirvana, which provides access to classes
* representing events and dictionaries.
* In this demo, we shall subscribe to a channel and define what we
* want to happen when certain activities occur (such as subscribing,
* or receiving events). We do this by implementing callback logic,
* either with anonymous functions, or if preferred, with named functions:
*********************************************************************/

//Obtain channel from the session that was created
var demoChannel = session.getChannel(channelName);
demoChannel.subscribe();

var isSubscribed = demoChannel.isSubscribed();
if(isSubscribed){
window.status = "Subscribed to " + demoChannel;
}

demoChannel.on(Nirvana.Observe.DATA, demoEventHandler);
demoChannel.onPublish = updateUserInputUI;



onConnect = function() { window.status = "Connected"; }
onDisconnect =
function() { window.status = "Disconnected. Reconnecting..."; }

/********************************************************************
* Now that we have defined all that should happen when our session is
* up and running, let us *start* it.
*********************************************************************/
}

function demoEventHandler(event) {

/********************************************************************
* This method automatically gets invoked every time we receive an
* event from the demoChannel (since this is the method we specified
* as the demoChannel.onData event handler. Note that the
* event object will be passed to this method as a parameter. We can
* then get the event's data "dictionary", and read the value of any
* of its keys. In this demo, we use this data to update a textarea.
*********************************************************************/

var dictionary = event.getDictionary();
var newData =
dictionary.get('publisher') + ": " + dictionary.get('message') + "\n"
var oldData = document.getElementById("outputTextarea").value;
document.getElementById("outputTextarea").value = newData + oldData;
}

function publishMessage() {

/********************************************************************
* This method is an example of how to publish events to our channel.
* We first get myChannel from an already created session,
* then we create an event myEvent - empty Universal Messaging <Event>,
* we create dictionary variable(myDict), and put the string
* from the html input. Finally, we call the channel's publish method,
* It is good practice to wrap code like this in try/catch blocks.
*********************************************************************/

if (document.getElementById("demoInput").value == "") return;
try {

var myChannel = session.getChannel(channelName);
var myEvent = Nirvana.createEvent();
var myDict = myEvent.getDictionary();
myDict.putString("message", document.getElementById("demoInput").value);
myDict.putString("publisher", demoUsername);
myChannel.publish(myEvent);

} catch (error) {
alert("Error: " + error.message);
}
}


function updateUserInputUI() {

/********************************************************************
* This method automatically gets invoked after we successfully
* publish to testChannel (since this is the method we specified
* as the handler for testChannel.onPublish.
* A typical implementation of such a function would re-enable UI components
* that might have been disabled while publishing took place.
*********************************************************************/

if(!initialiasedASession)
alert("We did not get a session to Universal Messaging");
document.getElementById("demoInput").value = "";
window.status = "Published";
}


</script>
<title>Universal Messaging JavaScript Tutorial Application:
Simple Chat Room</title>
</head>
<body onload="isLoaded()">
<h1>Universal Messaging JavaScript Tutorial Application:
Simple Chat Room</h1>

<form onsubmit="publishMessage(); return false;">

<h2>Input</h2>
<input type="text" id="demoInput"/>
<input type="submit" value="Publish">

<h2>Output</h2>
<textarea id="outputTextarea" rows="10" cols="70"></textarea>

</form>

</body>
</html>