DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Data Engineering
  3. IoT
  4. MQTT Over WebSockets with JavaScript and ActiveMQ

MQTT Over WebSockets with JavaScript and ActiveMQ

Michael Mainguy user avatar by
Michael Mainguy
·
Dec. 31, 13 · Interview
Like (0)
Save
Tweet
Share
20.91K Views

Join the DZone community and get the full member experience.

Join For Free

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>





MQTT WebSocket JavaScript

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

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • What Is Policy-as-Code? An Introduction to Open Policy Agent
  • The Role of Data Governance in Data Strategy: Part II
  • What Was the Question Again, ChatGPT?
  • Taming Cloud Costs With Infracost

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: