我正在使用socket.io,node.js和node.js MQTT客户端从HTMLS页面连接到在A-MQ上运行的代理。我可以成功连接到代理并订阅我需要的主题,但是我从来没有从主题中收到任何消息,即使有几个已经入队。
这是我的代码:
subscribe.js
var sys = require('sys');
var net = require('net');
var mqtt = require('mqtt');
var io = require('socket.io').listen(5000);
io.set('origins', '*:*');
var client = mqtt.connect("mqtt:admin:admin@//localhost:1883");
io.sockets.on('connection', function (socket) {
socket.on('subscribe', function (data) {
console.log('Subscribing to '+data.topic);
socket.join(data.topic);
client.subscribe(data.topic);
});
});
client.addListener('mqttData', function(topic, payload){
sys.puts(topic+'='+payload);
io.sockets.emit('mqtt',{'topic':String(topic),
'payload':String(payload)});
});
的index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>IoT Demo</title>
<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
<script type="text/javascript" src="js/socket.io.js"></script>
<script type="text/javascript">
var socket = io.connect('http://localhost:5000');
socket.on('connect', function () {
socket.on('mqtt', function (msg) {
var elmarr=msg.topic.split("/");
var elm=elmarr[3];
console.log(msg.topic+' '+msg.payload);
$('#'.concat(elm)).html(msg.payload);
});
socket.emit('subscribe',{topic:'customerenter'});
socket.emit('subscribe',{topic:'customermove'});
socket.emit('subscribe',{topic:'customerexit'});
});
</script>
</head>
<body>
<div style="position: absolute; top: 5px; left: 5px;">
</div>
</body>
</html>
在Chrome中调试时,
socket.on('mqtt', function (msg)
永远不会被执行。
有什么想法吗?
谢谢, 泰德
答案 0 :(得分:0)
假设你使用来自npm(https://www.npmjs.com/package/mqtt)的Mqtt客户端,那么mqtt客户端应该有一个on'message'回调集来处理传入的消息,而不是mqttData listener
client.on('message', function(topic, message){
sys.puts(topic+'='+message);
io.sockets.emit('mqtt',{'topic':String(topic),
'payload':String(message)});
});