Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

MQTT Over WebSockets with JavaScript and ActiveMQ

DZone's Guide to

MQTT Over WebSockets with JavaScript and ActiveMQ

· Integration Zone
Free Resource

Modernize your application architectures with microservices and APIs with best practices from this free virtual summit series. Brought to you in partnership with CA Technologies.

After reading up a bit about MQTT, I decided to set up a test bed to see how it works and if it lives up to its potential. The use case was simple: I wanted to build a multi-user chat system that would use MQTT over WebSockets connected directly to an Apache ActiveMQ server.

First off, I fired up an EC2 instance with Ubuntu-13.04 and tried to apt-get ActiveMQ. It turns out, however, to use MQTT over WebSockets, you need version 5.9 of ActiveMQ, so I pulled a snapshot version of ActiveMQ. Enabling MQTT over websockets is a snap. You simply add the following configuration to your activemq.xml:

<transportConnector name="mqtt+ws" uri="ws://0.0.0.0:1884maximumConnections=1000&wireFormat.maxFrameSize=104857600"/>

Next, download the Eclipse Paho MQTT client and create a web page to send traffic back and forth.

One last thing I did was install Apache HTTP on the same server as the ActiveMQ instance. I did this to avoid any potential problems with same origin policies.

At this point, I create a page that uses the MQTT client, and I can publish and subscribe to messages that will get pushed to the browser in real-time. My example is posted below (note, the AWS instance in the connect string is no longer valid, so you need to use your own server):

<html>
    <head>
        <title>MQTT over websockets</title>
        <style type="text/css">
            #status {
                padding: 5px;
                display: inline-block;
            }
            label, .label {
                display: inline-block;
                width: 100px;
            }
            li {
                list-style: none;

                background: #fff;
                margin: 2px;
            }
            ul {
                background: #eef;
            }
            .disconnected {
                background-color: #f88;
            }
            input {
                width: 400px;
            }
            .connected {
                background-color: #8f8;
            }

            #messagelist {
                width: 600px;
                height: 200px;
                overflow-y: scroll;
            }
        </style>
    </head>
    <body>
        <h1>Super simple chat</h1>
        <span class='label'>Status</span> <div id="status" class="disconnected">Pending</div>
        <form id='mainform' action="#">
            <label for="name">Name</label>
            <input id="name" name="name" type="text" width="40" value="anonymous"/> <br/>
            <label for="message">Message</label>
            <input id="message" name="message" type="text" width="200"/>
            <input id="submit" type="submit" value="go"/>
        </form>

        <div id="messages"><ul id="messagelist">

        </ul></div>

    <script src="./mqttws31.js"></script>
    <script src="./jquery-1.10.2.js"></script>
    <script>
    $(document).ready(function() {
        function doSubscribe() {

        }

        $('#mainform').submit(function(){
            var messageinput = $('#message');
            message = new Messaging.Message(messageinput.val());
            message.destinationName = "/can/"+$('#name').val();
            messageinput.val('');
            messageinput.focus();
            client.send(message);
            return false;
        });


        function doDisconnect() {
            client.disconnect();
        }

        // Web Messaging API callbacks
        var onSuccess = function(value) {
            $('#status').toggleClass('connected',true);
            $('#status').text('Success');
        }

        var onConnect = function(frame) {
            $('#status').toggleClass('connected',true);
            $('#status').text('Connected');
            client.subscribe("/can/#");
            //var form = document.getElementById("example");
            //form.connected.checked= true;
        }
        var onFailure = function(error) {
            $('#status').toggleClass('connected',false);
            $('#status').text("Failure");
        }

        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) {
            $('#messagelist').prepend('<li>'+message.destinationName+ '->' +message.payloadString+'</li>');
            //var form = document.getElementById("example");
            //form.receiveMsg.value = message.payloadString;
        }

        var client;
        var r = Math.round(Math.random()*Math.pow(10,5));
        var d = new Date().getTime();
        var cid = r.toString() + "-" + d.toString()

        client = new Messaging.Client("ec2-54-242-185-231.compute-1.amazonaws.com", 1884, cid );
        client.onConnect = onConnect;
        client.onMessageArrived = onMessageArrived;
        client.onConnectionLost = onConnectionLost;
        client.connect({onSuccess: onConnect, onFailure: onFailure});

    });

    </script>
    </body>
</html>





The Integration Zone is proudly sponsored by CA Technologies. Learn from expert microservices and API presentations at the Modernizing Application Architectures Virtual Summit Series.

Topics:

Published at DZone with permission of Michael Mainguy, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}