本文介绍了未使用带有Socket.IO的node.js MQTT客户端接收消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Socket.IO、node.js和node.js MQTT客户端从HTMLS页面连接到在A-MQ上运行的代理。我可以成功地连接到代理并订阅我需要的主题,但我从未从这些主题收到任何消息,即使有几条已入队。以下是我的代码:
订阅.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)
从不执行。
有什么想法吗?
谢谢,Ted
推荐答案
假设您从npm(https://www.npmjs.com/package/mqtt)使用mqtt客户端,那么mqtt客户端应该设置一个on‘Message’回调来处理传入消息,而不是mqtData侦听器
client.on('message', function(topic, message){
sys.puts(topic+'='+message);
io.sockets.emit('mqtt',{'topic':String(topic),
'payload':String(message)});
});
这篇关于未使用带有Socket.IO的node.js MQTT客户端接收消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!