mosca icon indicating copy to clipboard operation
mosca copied to clipboard

Mosca and mqtt don't get messages from browserified mqtt web client

Open mckennatim opened this issue 10 years ago • 21 comments

Following the tips from MQTT-over-Websockets I tried to add to this alredy working setup. server(broker)

var mosca = require('mosca')
var settings = {
  port: 1883,
  persistence: mosca.persistence.Memory,
  http: {port: 3333, bundle: true, static: './'}  
};
var server = new mosca.Server(settings, function() {
  console.log('Mosca server is up and running')
});
server.published = function(packet, client, cb) {
  if (packet.topic.indexOf('echo') === 0) {
    return cb();
  }
  var newPacket = {
    topic: 'echo/' + packet.topic,
    payload: packet.payload,
    retain: packet.retain,
    qos: packet.qos
  };
  console.log('newPacket', newPacket);
  server.publish(newPacket, cb);
}

client2.js

var mqtt = require('mqtt')
client = mqtt.createClient(1883, 'localhost');
client.subscribe('presence');
client.on('message', function(topic, message) {
    console.log(message.toString());
});
console.log('Client started...');    

client1.js

var mqtt = require('mqtt')
client = mqtt.createClient(1883, 'localhost');
client.subscribe('presence');
console.log('Client publishing.. ');
client.publish('presence', 'Client 10 is alive.. Test Ping! ' + Date());
client.end();

So I want to get a web client working and I followed the instructions in mqtt in browser w webpack to create browserMqtt.js

cd node_modules/mqtt
npm install . // install dev dependencies 
webpack mqtt.js ./browserMqtt.js --output-library mqtt

and used it in a webpage mimiking what the node client2.js already does.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>webmqtt</title>
    <script src="./dist/browserMqtt.js"></script>   
</head>
<body>
    <h1>hello</h1>
    <script>
        client = mqtt.connect({ host: 'localhost', port: 3333 });
        client.subscribe('presence');
        client.on('message', function(topic, payload) {
            console.log(message.toString())
        });
        client.publish('presence', 'Web Client is alive.. Test Ping! ' + Date());
    </script>
</body>
</html>  

It's publish message isn't showing up on the other clients and it doesn't get the messages it is subscribed to. It does however cause a new packet to arrive at the server with what looks like the browser client's id.

mckennatim avatar Jan 19 '16 13:01 mckennatim

When using a web browser you should connect via websockets protocol to the broker: mqtt.connect('ws://localhost:3333')

psorowka avatar Jan 19 '16 13:01 psorowka

Ok with that change...

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>webmqtt</title>
    <script src="./dist/browserMqtt.js"></script>   
</head>
<body>
    <h1>hellop</h1>
    <script>
        var client = mqtt.connect('ws://localhost:3333');
        console.log('maybe connected')
        client.subscribe('presence');
        client.on('message', function(topic, payload) {
            console.log(message.toString())
        });
        client.publish('presence', 'Web Client is alive.. Test Ping! ' + Date());
        //client.end()
    </script>
</body>
</html>

It still sendd the id but doesn't send or recieve messages

I thought maybe I wasn't allowing for a callback so I also tried this to no avail.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>webmqtt</title>
    <script src="./dist/browserMqtt.js"></script>   
</head>
<body>
    <h1>hellop</h1>
    <script>
        mqtt.connect('ws://localhost:3333', function(client){
            console.log('maybe connected')
            client.subscribe('presence');
            client.on('message', function(topic, payload) {
                console.log(message.toString())
            });
            client.publish('presence', 'Web Client is alive.. Test Ping! ' + Date());
        });
        //client.end()
    </script>
</body>
</html>

mckennatim avatar Jan 19 '16 14:01 mckennatim

@mckennatim

client.on('message', function(topic, payload) {
    console.log(message.toString());
});

There is payload instead of message.. maybe it helps

bossqone avatar Jan 19 '16 15:01 bossqone

payload instead of message didn't help

client.on('message', function(topic, payload) {
    console.log(payload.toString())
    console.log(payload)
    console.log(topic)
});

client.on('payload', function(topic, payload) {
    console.log(payload.toString())
    console.log(payload)
    console.log(topic)
});    

mckennatim avatar Jan 19 '16 16:01 mckennatim

How about something like this?

import mqtt from 'mqtt';
const client = mqtt.connect('mqtt://localhost:3333'); // <---

client.on('message', (topic, message) => {
    console.info('%s ->', topic, message);
});

client.on('connect', () => {
    console.info('Connected', Date.now());
});

nightwolfz avatar Jan 19 '16 16:01 nightwolfz

Tried @nightwolfz 's syntax...It stil sends the id but doesn't send or recieve messages

mckennatim avatar Jan 19 '16 16:01 mckennatim

It does connect every minute though.

mckennatim avatar Jan 19 '16 16:01 mckennatim

Which mosca version are you using?

psorowka avatar Jan 19 '16 18:01 psorowka

with npm install mosca --save I got "0.32.1"

mckennatim avatar Jan 19 '16 21:01 mckennatim

using node 4.2.3, npm 2.14.7

mckennatim avatar Jan 19 '16 21:01 mckennatim

Reinstalling now

mckennatim avatar Jan 19 '16 21:01 mckennatim

Now at mosca 1.0.1, BTW Pasho via mqttws31-min.js web client pub/subs to mosca server just fine but browserMqtt.js still does not.

mckennatim avatar Jan 19 '16 21:01 mckennatim

Have you tried this syntax?

var socket  = mqtt.connect(); // no args

socket.subscribe(topic, {qos: 1}, function() {
    socket.publish(topic, 'testttData');
});

Otherwise give us something more to work with... like what's happening in Chrome's network tab.

nightwolfz avatar Jan 19 '16 22:01 nightwolfz

Without args that code defaults to ws://localhost but I have set the http port in mosca to 3333 (works for paho). Network tab shows

Request URL:ws://localhost:3333/ Request Method:GET Status Code:101 Switching Protocols Response Headers view parsed HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: vJh1A9erFLwcTZ2PnfOhO5SN0NI= Sec-WebSocket-Protocol: mqttv3.1 Sec-WebSocket-Extensions: permessage-deflate Request Headers view source Accept-Encoding:gzip, deflate, sdch Accept-Language:en-US,en;q=0.8 Cache-Control:no-cache Connection:Upgrade Host:localhost:3333 Origin:http://localhost Pragma:no-cache Sec-WebSocket-Extensions:permessage-deflate; client_max_window_bits Sec-WebSocket-Key:OXIxbFAhTWME997HpFAfiw== Sec-WebSocket-Protocol:mqttv3.1 Sec-WebSocket-Version:13 Upgrade:websocket User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.0 Safari/537.36

timing 10 second stall, 5 seconds content

mckennatim avatar Jan 19 '16 22:01 mckennatim

Tim,

I just had a closer look to your setup.

First, on server side

I recommend using:

  var newPacket = {
    topic: 'echo/' + packet.topic,
    payload: packet.payload,
    retain: packet.retain || false,
    qos: packet.qos || 0
  };

because packet.retain and packet.qos might well be not defined and this way get a default value.

second, on client side

mqtt.connect does not take a callback function as an argument, instead you are required to use the event listener. You may issue the subscribe and publish functions only after the client is connected, thus you have to wrap them in a callback function which listens on the connect event, like this:

      var client = mqtt.connect('ws://localhost:3333')

      client.on('connect', function(){

        console.log('maybe connected')
        client.subscribe('presence')
        client.on('message', function(topic, payload) {
            console.log(payload)
        })
        client.publish('presence', 'Web Client is alive.. Test Ping! ' + Date())
      })

and btw, sure fancy ES6 syntax works, but naturally makes no difference:

      var client = mqtt.connect('ws://localhost:3333')

      client.on('connect', () => {

        console.log('maybe connected')
        client.subscribe('presence')
        client.on('message', (topic, payload) => console.log(payload))
        client.publish('presence', 'Web Client is alive.. Test Ping! ' + Date())
      })

UPDATE: this should also be required for a reliable behavior in the non-browser clients

psorowka avatar Jan 19 '16 23:01 psorowka

@psorowka, I added server defaults and went back to the async web client

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>webmqtt</title>
    <script src="./dist/browserMqtt.js"></script>   
</head>
<body>
    <h1>hellop</h1>
    <script>
        var client = mqtt.connect('ws://localhost:3333')
        client.on('connect', function(){
            console.log('maybe connected')
            client.subscribe('presence');
            client.on('message', function(topic, payload) {
                console.log(payload)
                console.log(payload.toString())
            });
            client.publish('presence', 'Web Client is alive.. Test Ping! ' + Date());
        });
    </script>
</body>
</html>    

mckennatim avatar Jan 20 '16 02:01 mckennatim

So, what is your result?

The code I pasted above works for me. Only difference I see is that I used the mqtt.js file that can be found in the mosca public folder for <script> tag.

psorowka avatar Jan 20 '16 08:01 psorowka

Back to it. At some point last night I was not updating the file I was displaying. It is working now, even with browserMqtt.js. Thank you @psorowka and @nightwolfz. This is going to change a lot about what I do. Works sweet with my esp8266's. Now its running straight through from little devices right to the browser. A new dimension has been added to 'responsive web apps' This is cooler than socket.io!

mckennatim avatar Jan 20 '16 21:01 mckennatim

I came across with similar issue today and finally found this link which solved my problem

var settings = {
    port: 1883,
    backend: pubsubsettings,
    http: {
        port: 1884,
        bundle: true,
        static: './'
    },
    persistence: {
        factory: mosca.persistence.Mongo,
        url: 'mongodb://localhost:27017/mqtt'
    }
};

Most import thing to note is http configuration which enables WS listener.

From browser, you need to connect to 1884 not 1883 ( you still need to connect to 1883 if connecting from node.js client )

 var client = mqtt.connect('ws://localhost:1884',{
            clientId:'chrome'
        });

just4give avatar Jun 07 '16 00:06 just4give

I guess you forget to configure mosca for web sockets.

ompurwar avatar Oct 07 '18 18:10 ompurwar