基于NodeJs建设MQTT服务
使用NodeJs建设MQTT模式;
很常规的需要引入mqtt包,npm install mqtt --save,耐心等待,这一步基本上都没问题;
那么在服务端还需要mosca服务,同样,npm install mosca --save。但是在这一步下载时会出现不少问题,如:
(1)需要前置下载好python环境
(2)NodeJs版本不能过高,要在2.5-3.0之间
(3)不支持visual studio 2017,需要下载visual studio 2015
(4)报错:C:WindowsMicrosoft.NETFrameworkv4.0.30319msbuild.exe` failed with exit code: 1 此抱错需要install另外两个环境(备注:需要用“以管理员权限运行”,否则第二个安装不了),npm install -g node-gyp ; npm install --global --production window-build-tools;
可能还会遇到其他的;
贴两个代码以方便测试
1、服务端 (启动命令 node mqtt-server.js)
//var mosca = require("../../../root/node_modules/mosca");
var mosca = require("mosca");
var ascoltatore = {
//using ascoltatore
//type: "mongo",
//url: "mongodb://localhost:27017/mqtt",
//pubsubCollection: "ascoltatori",
//mongo: {}
};
var settings = {
port: 1883,
backend: ascoltatore
};
var server = new mosca.Server(settings);
server.on("clientConnected", function(client) {
console.log("client connected", client.id);
});
// fired when a message is received
server.on("published", function(packet, client) {
console.log("Published", packet.payload);
});
server.on("ready", setup);
// fired when the mqtt server is ready
function setup() {
console.log("Mosca server is up and running");
}
2、客户端(node mqtt-test.js)
//var mqtt = require("../../../root/node_modules/mqtt/mqtt")
var mqtt = require("/node_modules/mqtt/mqtt")
var client = mqtt.connect("mqtt://test.mosquitto.org") //这里是公共测试地址,如果想要本地测试则改成127.0.0.1,服务器测试直接写服务器IP地址
client.on("connect", function () {
client.subscribe("presence")
client.publish("presence", "Hello mqtt")
})
client.on("message", function (topic, message) {
// message is Buffer
console.log(message.toString())
client.end()
})
以上是 基于NodeJs建设MQTT服务 的全部内容, 来源链接: utcz.com/z/513879.html