MQTT Websocket Client Connectivity

Text Copied

Introduction

This guide offers detailed, step-by-step instructions for connecting clients to our MQTT broker (CrysqlMQ) or any broker of your choice using JavaScript. It covers the necessary prerequisites and setup, guiding you through the process of establishing a reliable connection. You'll learn how to implement authentication, manage subscriptions, and handle message exchanges. With the help of this documentation, you'll be able to seamlessly integrate JavaScript web clients with the MQTT broker for efficient data communication.

Pre-requisites

Add the below plugin to your client file

<script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>

MQTT Connect

Basic TCP Connection


const clientId = 'testclient3';
const mqttV4Options = {
	clientId: clientId,
	hostname: 'broker-url',
	port: 10443,
	protocol: 'ws',
};
const mqttV4Client = mqtt.connect(`ws://${mqttV4Options.hostname}:${mqttV4Options.port}`, mqttV4Options);


Connect with Authentication:


const mqttV4Options = {
            clientId: clientId,
            hostname: 'broker-url',
            port: 10443,
            protocol: 'ws', // MQTT protocol
            username: 'username', // Add username if needed
            password: 'password', // Add password if needed
};


Connect over TLS/SSL

To connect securely using TLS/SSL:


const mqttV4Options = {
    clientId: clientId,
    hostname: 'broker-url',
    port: 11443,
    protocol: 'wss', 
    rejectUnauthorized: true, // Optional, reject unauthorized certificates
    // Add additional TLS options as needed
    cert: 'yourClientCert', // Client certificate
    key: 'yourClientKey', // Client key
    ca: 'yourCaCert' // CA certificate
};
const mqttV4Client = mqtt.connect(`wss://${mqttV4Options.hostname}:${mqttV4Options.port}`, mqttV4Options);

MQTT Publish

To send data to a topic:


window.publishMessageV4 = function (topic, message) {
    mqttV4Client.publish(topic, message, { qos: 1 }, (err) => {
        if (!err) {
            console.log(`Published message on MQTT v4: ${topic} - ${message}`);
        } else {
            console.error(`Failed to publish message on MQTT v4: ${err}`);
        }
    });
};

MQTT Subscribe

To receive messages, subscribe to a topic filter. The MQTT broker will forward matching messages to your client.


window.subscribeToTopicV4 = function (topic) {
    mqttV4Client.subscribe(topic, (err) => {
        if (!err) {
            console.log(`Subscribed to MQTT v4 topic: ${topic}`);
        } else {
            console.error(`Failed to subscribe to MQTT v4 topic: ${err}`);
        }
    });
};

Call back that receives the message


mqttV4Client.on('message', (topic, message) => {
    console.log(`Received message on MQTT v4: ${topic} - ${message.toString()}`);
});

MQTT Disconnect

Always disconnect cleanly to avoid resource leaks and ensure proper session handling on the broker:


window.disconnectClientV4 = function () {
    mqttV4Client.end(true, () => {
        console.log('Disconnected MQTT v4 client.');
    });
};


Disconnect callback


mqttV4Client.on('close', () => {
    console.log('Disconnected from MQTT v4 Broker.');
});

Sample MQTTv311 Client

Sample HTML code

MQTT 3.1.1 html file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>MQTT Example</title>
<script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
<script src="mqtt-v4.js" type="text/javascript"></script>
</head>
<body>
<h1>MQTT Example</h1>
<!-- MQTT v4 Section -->
<h2>MQTT v4</h2>
<p><strong>Client ID:</strong> <span id="mqttV4ClientId"></span></p>
<p><strong>Status:</strong> <span id="mqttV4Status">Disconnected</span></p>
<button onclick="disconnectClientV4()">Disconnect MQTT v4</button>
<hr>
<h3>Subscribe</h3>
<input type="text" id="mqttV4SubscribeTopic" placeholder="Topic to subscribe">
<button onclick="subscribeToTopicV4(document.getElementById('mqttV4SubscribeTopic').value)">Subscribe</button>
<p><strong>Subscribed to:</strong> <span id="mqttV4Subscribed"></span></p>
<hr>
<h3>Publish</h3>
<input type="text" id="mqttV4PublishTopic" placeholder="Topic to publish">
<input type="text" id="mqttV4PublishMessage" placeholder="Message to publish">
<button
onclick="publishMessageV4(document.getElementById('mqttV4PublishTopic').value, document.getElementById('mqttV4PublishMessage').value)">Publish</button>
<h3>Published Messages</h3>
<ul id="mqttV4Published"></ul>
<h3>Received Messages</h3>
<ul id="mqttV4Received"></ul>
</body>
</html>


Sample JavaScript code


document.addEventListener('DOMContentLoaded', (event) => {
    function main() {
        const clientId = 'testclient1';
        document.getElementById('mqttV4ClientId').textContent = clientId;
        const mqttV4Options = {
            clientId: clientId,
            hostname: 'broker-url',
            port: 10443,
            protocol: 'ws',
            // username: 'username', // Add username 
            // password: 'password', // Add password 
        };
        const mqttV4Client = mqtt.connect(`ws://${mqttV4Options.hostname}:${mqttV4Options.port}`, mqttV4Options);
        mqttV4Client.on('connect', () => {
            console.log('Connected with MQTT v4 Broker.');
            document.getElementById('mqttV4Status').textContent = 'Connected';
        });
        mqttV4Client.on('message', (topic, message) => {
            console.log(`Received message on MQTT v4: ${topic} - ${message.toString()}`);
            document.getElementById('mqttV4Received').innerHTML += `
  • Topic: ${topic}, Message: ${message.toString()}
  • `; }); mqttV4Client.on('close', () => { console.log('Disconnected from MQTT v4 Broker.'); document.getElementById('mqttV4Status').textContent = 'Disconnected'; }); window.publishMessageV4 = function (topic, message) { mqttV4Client.publish(topic, message, { qos: 1 }, (err) => { if (!err) { console.log(`Published message on MQTT v4: ${topic} - ${message}`); document.getElementById('mqttV4Published').innerHTML += `
  • Published to ${topic}: ${message}
  • `; } else { console.error(`Failed to publish message on MQTT v4: ${err}`); } }); }; window.subscribeToTopicV4 = function (topic) { mqttV4Client.subscribe(topic, (err) => { if (!err) { console.log(`Subscribed to MQTT v4 topic: ${topic}`); document.getElementById('mqttV4Subscribed').textContent = topic; } else { console.error(`Failed to subscribe to MQTT v4 topic: ${err}`); } }); }; window.disconnectClientV4 = function () { mqttV4Client.end(true, () => { console.log('Disconnected MQTT v4 client.'); document.getElementById('mqttV4Status').textContent = 'Disconnected'; }); }; } main(); });

    MQTT v5 client

    Sample HTML code

    <MQTT 5 html file> <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MQTT Example</title>
    <script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
    <script src="mqtt-v5.js" type="text/javascript"></script>
    </head>
    <body>
    <h1>MQTT Example</h1>
    <!-- MQTT v5 Section -->
    <h2>MQTT v5</h2>
    <p><strong>Client ID:</strong> <span id="mqttV5ClientId"></span></p>
    <p><strong>Status:</strong> <span id="mqttV5Status">Disconnected</span></p>
    <button onclick="disconnectClientV5()">Disconnect MQTT v5</button>
    <hr>
    <h3>Subscribe</h3>
    <input type="text" id="mqttV5SubscribeTopic" placeholder="Topic to subscribe">
    <button onclick="subscribeToTopicV5(document.getElementById('mqttV5SubscribeTopic').value)">Subscribe</button>
    <p><strong>Subscribed to:</strong> <span id="mqttV5Subscribed"></span></p>
    <hr>
    <h3>Publish</h3>
    <input type="text" id="mqttV5PublishTopic" placeholder="Topic to publish">
    <input type="text" id="mqttV5PublishMessage" placeholder="Message to publish">
    <button
    onclick="publishMessageV5(document.getElementById('mqttV5PublishTopic').value, document.getElementById('mqttV5PublishMessage').value)">Publish</button>
    <h3>Published Messages</h3>
    <ul id="mqttV5Published"></ul>
    <h3>Received Messages</h3>
    <ul id="mqttV5Received"></ul>
    </body>
    </html>


    Sample JavaScript code

    
    document.addEventListener('DOMContentLoaded', (event) => {
        function main() {
            const clientId = 'testclient4';
            document.getElementById('mqttV5ClientId').textContent = clientId;
            const mqttV5Options = {
                clientId: clientId,
                hostname: 'broker-url',
                port: 10443,
                protocol: 'ws',
                protocolVersion: 5,   // Use MQTT v5
                clean: true,         // Start clean session
                // username: 'username',
                // password: 'password',
            };
            const mqttV5Client = mqtt.connect(`ws://${mqttV5Options.hostname}:${mqttV5Options.port}`, mqttV5Options);
    		// call backs
            mqttV5Client.on('connect', () => {
                console.log('Connected with MQTT v5 Broker.');
                document.getElementById('mqttV5Status').textContent = 'Connected';
            });
            mqttV5Client.on('message', (topic, message, packet) => {
                console.log(`Received message on MQTT v5: ${topic} - ${message.toString()}`);
                document.getElementById('mqttV5Received').innerHTML += `
  • Topic: ${topic}, Message: ${message.toString()}
  • `; }); mqttV5Client.on('close', () => { console.log('Disconnected from MQTT v5 Broker.'); document.getElementById('mqttV5Status').textContent = 'Disconnected'; }); // Publish function window.publishMessageV5 = function (topic, message) { mqttV5Client.publish(topic, message, { qos: 1, retain: false, properties: { messageExpiryInterval: 60 // Optional: expire after 60 seconds } }, (err) => { if (!err) { console.log(`Published message on MQTT v5: ${topic} - ${message}`); document.getElementById('mqttV5Published').innerHTML += `
  • Published to ${topic}: ${message}
  • `; } else { console.error(`Failed to publish message on MQTT v5: ${err}`); } }); }; // Subscribe function window.subscribeToTopicV5 = function (topic) { mqttV5Client.subscribe(topic, { qos: 0, properties: { // No Local, Retain As Published, etc. can go here if needed } }, (err, granted) => { if (!err) { console.log(`Subscribed to MQTT v5 topic: ${topic}`); document.getElementById('mqttV5Subscribed').textContent = topic; } else { console.error(`Failed to subscribe to MQTT v5 topic: ${err}`); } }); }; // Disconnect function window.disconnectClientV5 = function () { mqttV5Client.end(true, () => { console.log('Disconnected MQTT v5 client.'); document.getElementById('mqttV5Status').textContent = 'Disconnected'; }); }; } main(); });

    Bring MQTT to the Web!

    Boost Your JavaScript Apps with Our Broker

    Enable real-time updates, seamless communication, and scalable IoT solutions
    by connecting your JavaScript MQTT client to our broker.