Designing a browser based Chat Client using SimpleMQ

(Streaming Pub/Sub Messages Over WebSockets Using SMQ)

In this tutorial, we will design a HTML/JavaScript chat client that shows how to use the publish and subscribe features of SMQ. All chat clients will be both publishers and subscribers.

chat publish subscribe

Figure 1: All connected chat clients publish and subscribe to the same topic name. (Note: All messages will be routed via the SMQ broker.)

Creating an SMQ Broker

In the first step, we setup a broker so that we can later use this broker when we are testing our chat client. The Mako Server includes the SMQ broker in the Mako Server's resource file, mako.zip.

STEP 1: Create the following Lua Server Pages (LSP) script and save it as an LSP file (Click below and copy).

<?lsp    local smq = page.smq -- fetch from 'page' table    if not smq then -- first time accessed       smq = require"smq.hub".create() -- Create one broker instance       page.smq = smq -- Store (reference) broker instance    end    smq:connect(request) -- Upgrade HTTP(S) request to an SMQ connection ?>

The SMQ Broker Documentation includes the above example and provides an overview of how it works; thus we will not cover how the code works here.

STEP 2: Setup a broker as follows:

  1. Download and unpack the Mako Server
  2. Create a directory and give it a name such as "simplemq"
  3. Copy the above LSP page and save it in the new directory as simplemq/smq.lsp
  4. Start the Mako Server on the command line as follows: mako -l::simplemq

Result: The Mako Server should print a message to confirm that it has successfully loaded the "broker" app. The URL to the broker will be /smq.lsp. If you attempt to open this URL by using your browser, it will return a 404 page not found response. For security reasons, the broker instance always returns a HTTP status code (404) when a non SMQ client attempts to connect.

Creating a chat client in HTML and JavaScript

Creating an SMQ JavaScript client, subscribing to a topic, and publishing to a topic is illustrated in the following example:

var smq = SMQ.Client(SMQ.wsURL("/smq.lsp"));
smq.subscribe("BasicChat", {onmsg:onChatMsg, datatype:"text"});
smq.publish("Hello World!", "BasicChat");

Example 1: creating an SMQ client, subscribing to a topic, and publishing to a topic.

An SMQ client is created on line 1. The function SMQ.wsURL is a helper function that converts a relative path into a an absolute WebSocket path by making sure the URL starts with ws:// or wss://. The WebSocket protocol allows cross site connections, so you may hard code the URL to a different server (if) the HTML file is not stored on the same server as the one utilized to run the SMQ broker. In the case of the above example, the HTML file and broker must be on the same server.

We subscribe to the topic "BasicChat" on line two. The second parameter is the "option" object where we set the callback function that will be called when we get messages on the topic and the message type we expect. The SMQ JavaScript client can manage binary data, text, or JSON. The "datatype" parameter makes sure we receive the type we expect.

Assembling the complete chat client:

Example one above includes all JavaScript code required for publishing and receiving messages on the "BasicChat" topic. The next step is to design a complete chat client in HTML, CSS, and JavaScript code. Designing an SMQ web app in JavaScript requires some understanding of the document object model. In our example, we will use JQuery to dynamically add HTML elements when a message is received.

<html>
  <head>
    <title>SMQ Basic Chat Demo</title>
    <link rel="stylesheet" type="text/css" href="style.css"/> 
      <script src="/rtl/jquery.js"></script>
      <script src="/rtl/smq.js"></script>
      <script>
        $(function() {
            var smq = SMQ.Client(SMQ.wsURL("/smq.lsp"));
            function onChatMsg(msg,ftid) {
                $('#messages ul').append("<li>"+msg+"</li>");
            };
            function sendChatMsg() {
                smq.publish($('#msg').val(), "BasicChatMsg");
                $('#msg').val('');
                $('#msg').focus();
                return false;
            };
            smq.subscribe("BasicChatMsg", {onmsg:onChatMsg, datatype:"text"});
            $('form').submit(sendChatMsg);
            $('#msg').focus();
        });
      </script>
  </head>
  <body>
    <table class="BasicChat">
      <tr>
      <td>
        <div id="messages">
          <div><ul></ul></div> <!-- Messages will be injected here -->
          <form>
            <input id="msg" />
          </form>
        </div>
        </td>
      </tr>
    </table>
  </body>
</html>

Example 2: the complete chat client.

Line 5-6 JQuery and SMQ are included in the Mako Server resource file mako.zip, and we can simply instruct the browser to load these two libraries as shown on these two lines.

Line 8-22 shows typical JQuery startup code. We pass in an anonymous function to the JQuery "$" function. JQuery will then execute our anonymous function when the DOM is ready (when all required resources are loaded). See JQuery for details.

Line 10-12 is the callback function that will be called when we receive a message published to the "BasicChat" topic. This function appends the message as an <li> element to the <ul> element whose parent has the ID "messages". The HTML for this can be found on line 30.

Line 13-18 is the function that publishes messages to the "BasicChat" topic. This function extracts the text entered into the HTML element on line 32 and publishes the text. The sendChatMsg function is installed as an event function on line 20. The function gets called when you press the "ENTER" key.

The above HTML and JavaScript code is all that is needed for creating a basic chat client. A message is sent to all subscribers, including your own browser window. The example below should show a working BasicChat client unless you are using an archaic browser with no WebSocket support.

Example 4: chat client connecting to the broker simplemq.com.


Download Chat Client:

The server side code and the web application is included in the Mako Server Tutorials. See the online SMQ documentation for more information.

Improving the chat client

In the next tutorial, we will improve the chat client and introduce some of the unique features of the SMQ protocol.

Discover More:

Whether you are a maker, a startup, or a large business, we've got you covered. Please send us an email if you have any questions or if you are unsure on what product to select. We are here to help you find the best solution, and we'd really like to help you with your hardware/software project challenges.


OPC-UA

OPC-UA Client & Server

An easy to use OPC UA stack that enables bridging of OPC-UA enabled industrial products with cloud services, IT, and HTML5 user interfaces.

Edge Controller

Edge Controller

Use our user programmable Edge-Controller as a tool to accelerate development of the next generation industrial edge products and to facilitate rapid IoT and IIoT development.

On-Premises IoT

On-Premises IoT Platform

Learn how to use the Barracuda App Server as your On-Premises IoT Foundation.

Embedded Web Server

Barracuda Embedded Web Server

The compact Web Server C library is included in the Barracuda App Server protocol suite but can also be used standalone.

WebSocket Server

Microcontroller Friendly

The tiny Minnow Server enables modern web server user interfaces to be used as the graphical front end for tiny microcontrollers. Make sure to check out the reference design and the Minnow Server design guide.

WebDAV Server

Network File System

Why use FTP when you can use your device as a secure network drive.

HTTP Client

Secure HTTP Client Library

PikeHTTP is a compact and secure HTTP client C library that greatly simplifies the design of HTTP/REST style apps in C or C++.

WebSocket Client

Microcontroller Friendly

The embedded WebSocket C library lets developers design tiny and secure IoT applications based on the WebSocket protocol.

SMTP Client

Secure Embedded SMTP Library

Send alarms and other notifications from any microcontroller powered product.

Crypto Library

RayCrypto C Library

The RayCrypto engine is an extremely small and fast embedded crypto library designed specifically for embedded resource-constrained devices.

Embedded PKI Service

Automatic SSL Certificate Management for Devices

Real Time Logic's SharkTrust™ service is an automatic Public Key Infrastructure (PKI) solution for products containing an Embedded Web Server.

Modbus

Modbus TCP client

The Modbus client enables bridging of Modbus enabled industrial products with modern IoT devices and HTML5 powered HMIs.

Posted in SimpleMQ