Designing a browser based Chat Client using SimpleMQ

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,

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.

    <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>
        $(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");
                return false;
            smq.subscribe("BasicChatMsg", {onmsg:onChatMsg, datatype:"text"});
    <table class="BasicChat">
        <div id="messages">
          <div><ul></ul></div> <!-- Messages will be injected here -->
            <input id="msg" />

Example 2: the complete chat client.

Line 5-6 JQuery and SMQ are included in the Mako Server resource file, 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

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.

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

Posted in SimpleMQ