今天使用mosca 写了一下基于MQTT的消息服务端,用于下一个项目的知识储备;
该功能主要是基本 NODEJS 的 mosca 插件完成
1. 安装 mosca
npm install mosca --save
2. 创建mqtt服务端,端口为:8000
var mosca = require('mosca');var MqttServer = new mosca.Server({ port: 8000});
3. mqtt服务端部分逻辑处理
MqttServer.on('clientConnected', function(client){ console.log('client connected', client.id);});/** * 监听MQTT主题消息 **/MqttServer.on('published', function(packet, client) { var topic = packet.topic; switch(topic){ case 'pubMsg': console.log('message-publish', packet.payload.toString()); //MQTT转发主题消息 MqttServer.publish({topic: 'other', payload: 'sssss'}); //发送消息NODEJS console.log('HD: '+ YHSocketMap.get('1000')); //发送socket.io消息 //io.sockets.socket(YHSocketMap.get('1000')).emit('subState', packet); break; case 'other': console.log('message-123', packet.payload.toString()); break; }});MqttServer.on('ready', function(){ console.log('mqtt is running...');});
原文链接: