2015-10-18 132 views
0

我正在使用socket.io,node.js和node.js MQTT客戶端連接到從HTMLS頁面在A-MQ上運行的代理。我可以成功連接到代理並訂閱我需要的主題,但我從來沒有從主題中收到任何消息,即使有幾個消息被排隊。未使用node.js MQTT客戶端收到的消息使用socket.io

這裏是我的代碼:

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:[email protected]//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

假設你使用來自NPM(https://www.npmjs.com/package/mqtt)MQTT客戶機則MQTT客戶應該有一個對「消息」回調設置爲處理傳入的消息,而不是mqttData聽者

client.on('message', function(topic, message){ 
    sys.puts(topic+'='+message); 
    io.sockets.emit('mqtt',{'topic':String(topic), 
    'payload':String(message)}); 
}); 
+0

謝謝hardillb。我在另一篇文章中同時看到了你的答案。這是問題。 :) –

相關問題