How to program messaging apps in JavaScript

The MQTT messaging client for JavaScript includes a tutorial that demonstrates how to create a simple publish and subscribe web app. By exploring the "First steps, Hello world" application code, you can get a basic understanding of the mechanics of programming web apps for messaging.

If your experience to date has been mainly in developing and deploying traditional messaging applications, you might also find the JavaScript coding tips section helpful. If you are an experienced JavaScript developer who is new to messaging, you'll find a brief introduction to key messaging concepts in the Messaging basics section.

Messaging client for JavaScript tutorial page, which shows you how to code an app that subscribes to topic "World", and publishes a message "Hello" to it.

JavaScript coding tips

If you are used to developing messaging applications, but new to web apps, you might find the following tips helpful:
Wrapping the code for each event in an onSuccess callback
When you code a messaging application, you code the following events in the following order:
  1. connect
  2. subscribe
  3. publish
  4. receive message
The MQTT messaging client for JavaScript API is fully asynchronous, which means that your application thread does not block while waiting for calls like connect or subscribe to take effect. Instead these calls signal their completion by calling an onSuccess or onFailure callback. To be sure that each event has completed before the next event is triggered, you need to wrap the code for each event in an onSuccess callback. For example, the JavaScript application might return from making the connect call before the connection has been created. To be sure that connection has happened before you subscribe, you need to put the subscribe code in an onSuccess callback for the connect.
The "First steps, Hello world" application code uses this approach.
Embedding the application code within HTML mark-up
Here is an example JavaScript page:
MQTT messaging client for JavaScript example web messaging web page.
Here is the source for the previous page, to show how the application code is embedded within HTML mark-up:
<!DOCTYPE html>


<head>
  <script type="text/javascript" src="../WebSocket/mqttws31.js"></script>
  
  <script type="text/javascript">
  
  var client;
  var form = document.getElementById("tutorial");
  
  function doConnect() {
      client = new Messaging.Client("whistler1.hursley.ibm.com", 1883, "ClientId");
      client.onConnect = onConnect;
      client.onMessageArrived = onMessageArrived;
      client.onConnectionLost = onConnectionLost;
      client.connect({onSuccess:onConnect});
  }
  
  function doSubscribe() {
      client.subscribe("/World");
  }
  
  function doSend() {
      message = new Messaging.Message("Hello");
      message.destinationName = "/World";
      client.send(message);
  }

  function doDisconnect() {
      client.disconnect();
  }
  
  // Web Messaging API callbacks
  
  function onConnect() {
      var form = document.getElementById("example");
      form.connected.checked= true;
  }
  
  function onConnectionLost(responseObject) {
      var form = document.getElementById("example");
      form.connected.checked= false;
      if (responseObject.errorCode !== 0)
          alert(client.clientId+"\n"+responseObject.errorCode);
  }
  
  function onMessageArrived(message) {
      var form = document.getElementById("example");
      form.receiveMsg.value = message.payloadString;
  }
  
  </script>
</head> 

<body>
  <h1>Example Web Messaging web page.</h1>
  <form id="example">
  <fieldset>
  <legend id="Connect" > Connect </legend>
    Make a connection to the server, and set up a call back used if a 
    message arrives for this client.
    <br>
    <input type="button" value="Connect" onClick="doConnect(this.form)" name="Connect"/>
    <input type="checkbox" name="connected" disabled="disabled"/>
  </fieldset>
  
  <fieldset>
  <legend id="Subscribe" > Subscribe </legend>
  Make a subscription to topic "/World".
  <br> <input type="button" value="Subscribe" onClick="doSubscribe(this.form)"/>
  </fieldset>
  
  <fieldset>
  <legend id="Send" > Send </legend>
    Create a Message object containing the word "Hello" and then publish it at
    the server.
    <br>
    <input type="button" value="Send" onClick="doSend(this.form)"/>
  </fieldset>
  
  <fieldset>
  <legend id="Receive" > Receive </legend>
    A copy of the published Message is received in the callback we created earlier.
  <textarea name="receiveMsg" rows="1" cols="40" disabled="disabled"></textarea>
  </fieldset>
  
  <fieldset>
  <legend id="Disconnect" > Disconnect </legend>
    Now disconnect this client from the server.
  <br> <input type="button" value="Disconnect" onClick="doDisconnect()"/>
  </fieldset>
  </form>
</body>
</html>

Messaging basics

Here is some background messaging information for web app developers who are new to messaging:

Asynchronous and fire-and-forget messaging.
The MQTT protocol supports assured delivery and fire-and-forget transfers. In the protocol, message delivery is asynchronous: the app passes the message to the client API, and takes no further action to ensure that the message is delivered. This is approach is known as fire-and-forget. When a response is available, it is automatically sent to the app.
Asynchronous delivery frees up the app from any server connection, and from waiting for messages. The interaction model is like email, but optimized for application programming.
See also the MQTT protocol section of Introduction to MQTT
An overview of publish and subscribe messaging.
The provider of information is called a publisher. A publisher supplies information about a subject, without needing to know anything about the applications that are interested in that information. A publisher chooses a topic, which is a container for messages on a specific subject. The publisher then generates each piece of information for that subject as a message, called a publication, and posts it to the associated topic.
The consumer of information is called a subscriber. A subscriber creates a subscription to a topic that it is interested in. When a new message is posted to topic, the message is forwarded to all subscribers to the topic. Subscribers can make multiple subscriptions and can receive information from many different publishers.
See also Introduction to IBM® WebSphere® MQ publish/subscribe messaging
How subscriptions and topics match up.
If you are using IBM WebSphere MQ as your MQTT server, you need to understand how IBM WebSphere MQ specifies topics. In IBM WebSphere MQ, a publisher creates a message, and publishes it with a topic string that best fits the subject of the publication. To receive publications, a subscriber creates a subscription with a pattern matching topic string to select publication topics. The queue manager delivers publications to subscribers that have subscriptions that match the publication topic, and are authorized to receive the publications.
Typically subjects are organized hierarchically, into topic trees, using the '/' character to create subtopics in the topic string. Topics are nodes in the topic tree. Topics can be leaf-nodes with no further subtopics, or intermediate nodes with subtopics. Subscribers can use wildcards to subscribe to more than one topic at a time. For example, a subscription to /sport/tennis only gets messages posted to the tennis subtopic, whereas a subscription to /sport/# gets messages posted to any subtopic of /sport.
See also Topics, Topic trees, and Wildcard schemes.