node mosca mqtt Browserify I don't get message in the broker

1.5k Views Asked by At

I'm just playing around with mqtt && mosca

I've followed this steps:

npm install -g browserify // install browserify 
cd node_modules/mqtt
npm install . // install dev dependencies 
browserify mqtt.js -s mqtt > browserMqtt.js

index.html

<html>
  <head>
        <meta charset="utf-8" />
  </head>
  <body>
    <script src="./browserMqtt.js"></script>
      <script>
        var client = mqtt.connect({ host: 'localhost', port: 1884 }); 
        client.subscribe("presence");

        client.on("message", function(topic, payload) {
          console.log([topic, payload].join(": "));
          client.end();
        });

        client.publish("presence", "hello world!");
    </script> 
    </body>

</html>

server.js

var mosca = require('mosca')

//1883
var settings = {
  port: 1884
};

//here we start mosca
var server = new mosca.Server(settings);
server.on('ready', setup);

// fired when the mqtt server is ready
function setup() {
  console.log('Mosca server is up and running')
}

// fired whena  client is connected
server.on('clientConnected', function(client) {
  console.log('client connected', client.id);
});

// fired when a message is received
server.on('published', function(packet, client) {
  console.log('Published MIO: ', packet.payload);
});

// fired when a client subscribes to a topic
server.on('subscribed', function(topic, client) {
  console.log('subscribed : ', topic);
});

// fired when a client subscribes to a topic
server.on('unsubscribed', function(topic, client) {
  console.log('unsubscribed : ', topic);
});

// fired when a client is disconnecting
server.on('clientDisconnecting', function(client) {
  console.log('clientDisconnecting : ', client.id);
});

// fired when a client is disconnected
server.on('clientDisconnected', function(client) {
  console.log('clientDisconnected : ', client.id);
});

but if I run

node server

and than I go to my index.html I don't see any message in the console window where I've run the server.

With this (it's quite the same) I can see the message

client.js

var mqtt = require('mqtt')

var client = mqtt.connect({ host: 'localhost', port: 1884 });

client.subscribe('presence');

console.log('Client publishing.. ');
client.publish('presence', 'Client 1 is alive.. Test Ping! ' + Date());

client.end();

what's wrong ?

1

There are 1 best solutions below

3
On

This page explains it well: https://github.com/mcollina/mosca/wiki/MQTT-over-Websockets

Looking at your code you need to allow the mosca server to handle Websockets. Here is what you should change for your server settings.

updates to server.js:

var settings = {
    port: 1884,
    http: {
        port: 3000,
        bundle: true,
        static: './'
    }
};

updates to index.html:

var client = mqtt.connect({ host: 'ws://localhost', port: 3000 });