Node.js Mosca和mqtt don';t从浏览器化的mqtt web客户端获取消息
按照来自我尝试添加到这个alredy工作设置的提示。 服务器(代理) client2.jsNode.js Mosca和mqtt don';t从浏览器化的mqtt web客户端获取消息,node.js,websocket,browserify,webpack,mqtt,Node.js,Websocket,Browserify,Webpack,Mqtt,按照来自我尝试添加到这个alredy工作设置的提示。 服务器(代理) 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
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客户机工作,并按照中的说明创建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>
webmqtt
你好
client=mqtt.connect({host:'localhost',端口:3333});
客户。认购(“在场”);
client.on('message',函数(主题,负载){
console.log(message.toString())
});
publish('presence','Web客户端处于活动状态..测试Ping!'+Date());
它的发布消息没有显示在其他客户端上,并且它没有获得订阅的消息。但是,它确实会导致一个新数据包到达服务器,它看起来像是浏览器客户端的id。这可能是因为消息回调函数使用有效负载作为变量名,但您在函数中使用消息
message.toString()
应该是
payload.toString()
您在客户端使用了错误的端口号。应该是3333,而不是1883 1883对于本机MQTT,您为Websocket连接显示的配置是端口3333 您可能还应该在传递给连接的对象中包含协议
client = mqtt.connect({ host: 'localhost', port: 3333, protocol: 'ws' });
client = mqtt.connect({ host: 'localhost', port: 3333, protocol: 'ws' });