关于MQTT文章网上都是不够深刻。倒是nodemcu开发库这里,写得简单易懂,可以参考参考
http://nodemcu.readthedocs.io/en/master/en/modules/mqtt/#mqttclientsubscribe
====
先安装mqtt的包。npm install mqtt -g 和 npm install mosca -g
服务端代码mqserver.js
var moment = require('moment');
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'admin',
database : 'test'
});
connection.connect();
var userAddSql = 'INSERT INTO home(datetime,temp,humi) VALUES(?,?,?)'; //SQL插入语句格式
var userAddSql_Params = ['2018-7-1',27.4, 85]; //插入语句字段数据
var mosca = require('mosca');
var MqttServer = new mosca.Server({
port: 1883
});
MqttServer.on('clientConnected', function(client){
console.log('client connected', client.id);
});
MqttServer.on('subscribed', function(topic, client){ //订阅
console.log('subscribed: ', topic);
});
MqttServer.on('unSubscribed', function(topic, client){ //取消订阅
console.log('unSubscribed: ', topic);
})
MqttServer.on('clientDisConnected', function(client){
console.log('client connected', client.id);
});
/**
* 监听MQTT主题消息
**/
MqttServer.on('published', function(packet, client) {
var topic = packet.topic;
var qtt={}; //定义消息(可以为字符串、对象等)
qtt.topic='other';
qtt.payload='{"from":1977}';
switch(topic){
case 'hmdata':
console.log('mqtt-hmdata: ','topic ='+topic+',message = '+ packet.payload.toString());
//MqttServer.publish({topic: 'other', payload: 'sssss'});
MqttServer.publish(qtt); //推送一个json对象,这个推送自己也会收到。
//MqttServer.publish('other',JSON.stringify(qtt),{qos:1, retain: true});
var data=JSON.parse(packet.payload.toString()); //json解析
userAddSql_Params[0]=moment().format('YYYY-MM-DD HH:mm:ss'); //数组内容
userAddSql_Params[1]=data.temp;
userAddSql_Params[2]=data.humi;
connection.query(userAddSql,userAddSql_Params,function (err, result) { //sql插入数据
if(err){
console.log('[INSERT ERROR] - ',err.message);
return;
}});
break;
case 'other':
console.log('mqtt-other: ', packet.payload.toString());
break;
}
});
MqttServer.on('ready', function(){
console.log('mqtt is running...');
//MqttServer.authenticate = authenticate;
});
客户端mqclient.js
var mqtt = require('mqtt');
var client = mqtt.connect('mqtt://118.126.X.X:1883'); //连到腾讯云服务器。
//var client = mqtt.createClient(1883, 'localhost'); //这种方式不知道是哪里的,无效
var num = 0;
var qtt={}; //定义消息(可以为字符串、对象等)
qtt.temp=25.7 + Math.random()*5;
qtt.humi=89.1 + Math.random()*10;
qtt.count=0;
setInterval(function (){ //发布主题为‘test’的消息
qtt.count++;
qtt.temp=(25.7 + Math.random()*5).toFixed(2);
qtt.humi=(89.1 + Math.random()*10).toFixed(2); //2位小数
client.publish('hmdata',JSON.stringify(qtt),{qos:1, retain: true});// 'Hello mqtt ' + (num++)
}, 2000);
client.subscribe('hmdata',{qos:1}); //表示订阅这个hmdata消息。那么服务器推送这个hmdata时,自己才会收到,否则收不到。
client.on('message', function (topic, message) {
// message is Buffer
console.log('订阅的消息:'+topic + ','+ message.toString()); //打印消息内容
//client.end();
});
服务器显示结果:第二条消息是自己 推送的。第一条消息是客户端推送的。
客户端显示结果:取消订阅后,消息就收不到了。