Mosca和mqtt不会从browserfied mqtt web客户端获取消息

时间:2016-01-19 04:41:58

标签: node.js websocket browserify webpack mqtt

根据MQTT-over-Websockets的提示,我尝试添加到此alredy工作设置。 服务器(代理)

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();

所以我想让一个Web客户端工作,我按照mqtt in browser w webpack中的说明创建了browserMqtt.js

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

并在网页中使用它来模仿client2.js节点已经完成的工作。

<!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>  

它的发布消息没有显示在其他客户端上,并且它没有获得它订阅的消息。但它确实会导致新数据包到达服务器时看起来像浏览器客户端的ID。

2 个答案:

答案 0 :(得分:0)

这可能是因为消息回调函数使用有效负载作为变量名,但您在函数中使用了消息。

message.toString()

应该是

payload.toString()

答案 1 :(得分:0)

您在客户端使用错误的端口号。应该是3333而不是1883

1883用于本机MQTT,您为Websocket连接显示的配置是端口3333

您可能还应该在传递给连接的对象中包含协议

 client = mqtt.connect({ host: 'localhost', port: 3333, protocol: 'ws' });