赞
踩
使用nodejs编写一个简单的服务器,然后在编写两个客户端,一个客户端用来接收消息,另一个客户端用来发送消息:
服务器代码为:不过,你第一次运行的时候,会缺少mosca模块,自己npm install mosca即可。具体功能,学过编程的大致都能看懂,然后里面都有注释。
- var mosca = require('mosca');//构建服务器
- /*var settings = {
- port:8989,
- backend:{
- type:'zmq',
- json:false,
- zmq:require("zmq"),
- port:"tcp://127.0.0.1:33334",
- controlPort:"tcp://127.0.0.1:33334",
- delay:5
- },
- persistence: {
- factory:mosca.persistence.Mongo,
- url:"mongodb://localhost:270117/mosca"
- }
- };
- var MqttServer = new mosca.Server(settings);*/
- var MqttServer = new mosca.Server({
- port:8000
- });
-
- //监听链接
- MqttServer.on("clientConnected",function(client) {
- console.log("client connected",client.id);
- });
- //监听mqtt的主题消息
- MqttServer.on("published",function(packet,client) {//当客户端有连接的时候,发布主题消息
- var topic = packet.topic;
- console.log(packet);
- switch(topic) {
- case 'test':
- console.log("message-publish",packet.payload.toString());
- //mqtt转发主题消息
- MqttServer.publish({topic:'other',payload:'这是服务端!'});
- break;
- case 'test2':
- console.log("payload:",packet.payload.toString());
- var msg = {
- topic:'repeat',
- payload:packet.payload,
- qos:0,
- retain:false
- };
- MqttServer.publish(msg,function() {
- console.log('repeat! ');
- });
- break;
- case 'other':
- console.log("case-other:",packet.payload.toString());
- break;
- }
- });
- MqttServer.on('ready',function() {
- console.log("mqtt is running....");
- });
发送消息客户端:
- var mqtt = require('mqtt');
- var client = mqtt.connect('mqtt://192.168.1.136:8000');//连接到服务端
- var num = 0;
- var qtt = {};//定义消息(可以为字符串,对象等)
- qtt.aa = '发布';
- qtt.bb = '消息!';
-
- setInterval(function() {
- //发布主题为Test的消息
- client.publish('test',JSON.stringify(qtt),{qos:1,retain:true});//hello mqtt + num++
- },1000);
接收消息的客户端;
- var mqtt = require('mqtt');
- var client2 = mqtt.connect("mqtt://192.168.1.136:8000");
-
- client2.subscribe('test',{qos:1});//订阅主题为test的消息
-
- client2.on('message',function(top,message) {
- console.log(message.toString());
- });
至此第一个简单的nodejs版的mqtt的demo已经搭建完毕,后期具体的开发,见后文的博客!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。