MQTT over Websockets

Richard Joyce edited this page Jul 8, 2016 · 7 revisions

Since v0.13.0 Mosca support MQTT over Websocket through the MQTT.js package.

It is very easy to use:

Client side

We just use an index.html file to make the calls:

    <script src="/mqtt.js"></script>
      var client = mqtt.connect();


      client.on("message", function(topic, payload) {
        alert([topic, payload].join(": "));

      client.publish("mqtt/demo", "hello world!");

Standalone Mosca

We can use Mosca standalone, using the command line:

npm install mosca bunyan -g
mosca -v --http-port 3000 --http-bundle --http-static ./ | bunyan

Embedded Mosca

var mosca = require("mosca");
var server = new mosca.Server({
  http: {
    port: 3000,
    bundle: true,
    static: './'

Separate HTTP Server

We can also augment a node HTTP server with MQTT-over-websocket capabilities, just by calling the Server#attachHttpServer method, like so:

var http     = require('http')
  , httpServ = http.createServer()
  , mosca    = require('mosca')
  , mqttServ = new mosca.Server({});



MQTT.js Browserify Bundle

The browserified bundle for MQTT.js for the MQTT websocket client is available in the public folder of the Mosca module. You can serve it using express like so:

var mosca = require("mosca");
var broker = new mosca.Server({});
var express = require("express");
var http = require("http");
var app = express()
var srv = http.createServer(app)
var path = require("path");

app.use(express.static(path.dirname(require.resolve("mosca")) + "/public"))

You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.