Mosca 和 mqtt 不会从浏览器获取消息 mqtt Web 客户端



按照 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);
}

客户端2.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...');    

客户端1.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 客户端工作,我按照浏览器 w webpack 中 mqtt 中的说明创建了浏览器 Mqtt.js

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

并在网页中使用它来模拟 Node 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。

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

message.toString()

它应该是

payload.toString()

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

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

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

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

最新更新