Node.js实现mqtt发布/发送消息到主题什么是mqtt?我的博客写过这个东西:传送门安装首先需要安装node.js和npm教程传送门然后找个文件夹执行命令行安装mqtt模块;npminstallmqtt如果服务端需要执行npminstallmosca使用mqtt文档以下代码中的一些参数可以从mqtt官方文档mqttmoduledocumentationinnode.jsmqttprotocolentry文章servervarmosca=require('mosca');//搭建自己的服务器varMqttServer=newmosca.Server({port:1883});//配置服务器端口,监听该端口MqttServer.on('clientConnected',function(client){//监听连接console.log('clientconnected',client.id);});/***监听MQTT主题消息**/MqttServer.on('published',function(packet,client){//当客户端有发布主题消息的连接vartopic=packet.topic;console.log(packet);switch(topic){case'test':console.log('message-publish',packet.payload.toString());//MQTT转发主题消息MqttServer.publish({topic:'other',payload:'sssss'});break;case'other':console.log('message-123',packet.payload.toString());break;}});MqttServer.on('ready',function(){//服务启动时console.log('mqttisrunning...');});PS:不推荐使用Node.js作为服务器向主题发布消息varmqtt=require('mqtt');varclient=mqtt.connect('mqtt://127.0.0.1');//连接到服务器//client.subscribe('presence');varnum=0;varqtt={};//定义消息(可以是字符串,对象等)qtt='setr=xxxxxxx1xx';setInterval(function(){//每秒向主题SN69143809293670state发送一次消息,消息为setr=xxxxxxx1xxclient.发布('SN69143809293670state',qtt,{qos:0,保留:true});},1000);订阅主题varmqtt=require('mqtt');varclient2=mqtt.connect("mqtt://127.0.0.1:1883");//指定服务器地址和端口client2.subscribe('test',{qos:1});//订阅主题为test的消息client2.on('message',function(top,message){console.log(message.toString());});makeinterface(简体)我接触的物理设备向他发送控制或查询请求到他订阅的主题(ctr),它收到控制信息后执行。当执行成功时,状态会发送到另一个我订阅的主题中。用php实现比较麻烦,有时候没有信息返回。使用node.js更方便,信息返回更快;物理环境:centos7.264位,装有mqtt服务代理和node。js;需要安装http和express以及mqtt模块npminstall模块名称node.jshttp模块文档varmqtt=require('mqtt');varexpress=require("express");varapp=express();var主机名='127.0.0.1';//http服务提供ipvarport=8080;varnum=1;person=newObject();person.firstname="Bill";app.all('*',function(req,res,next){res.header("Access-Control-Allow-Origin","*");res.header("Access-Control-Allow-Headers","Origin,X-Requested-With,Content-Type,Accept");res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");res.header("X-Powered-By",'3.2.1')??res.header("Content-Type","application/json;charset=utf-8");next();});//json头app.get("/zhinengjiaju/get",function(req,res){//如果有是get请求/zhinengjiaju/get,执行回调中的代码(方便!)//console.log("requesturl:",req.path)//console.log("Requestparameters:",req.query)req.setTimeout(200);//设置请求建立200ms会中断请求的接受,但收到返回信息后仍会返回varclient=mqtt.connect('mqtt://127.0.0.1:1883',{用户名:'用户名',密码:'密码',clientId:'ap'+num});//建立连接client.on('connect',function(){varsn=req.query.sn;vark=parseInt(req.query.k)-1;//127.0.0.1:8080/zhinengjiaju/get?sn=SN69143809293670&k=1&v=3&cmd=setr客户端。订阅(sn+'状态',{qos:1});//开始订阅if(req.query.cmd!='setr'){m=req.query.cmd;if(req.query.cmd=='qk'){m='setr=1111111111';}if(req.query.cmd=='qg'){m='setr=0000000000';}}else{varm=['x','x','x','x','x','x','x','x','x','x'];m[k]=req.query.v;;m=req.query.cmd+'='+m.join('');}//一系列简单的接口处理client.publish(sn+'ctr',m,{qos:1,retain:true});//'Hellomqtt'+(num++)//发送client.end();//发送后立即结束与服务器建立的请求});client.on('message',function(topic,message){//订阅信息一直在运行,如果有设备返回信息给topic,执行这个回调aaak(消息.toString());//通过aaak函数将值传给res.end返回页面数据;客户端();});函数aaak(aaaa){varobjaaaa=JSON.parse(aaaa);//console.log(objaaaa);数++;客户端();res.end(aaaa);}})app.listen(port,hostName,function(){console.log(`服务器运行在http://${hostName}:${port}`);});感谢您的支持,感觉不错,打赏一下;
