我正在制作一个物联网项目,它使用 mosca 服务器、mqtt.js 和 express 以及 jQuery 来制作网络。我的目的是制作一个可以与某些嵌入式板(例如 Arduino、esp、...
当我向服务器发布一些消息时,我希望服务器发布回“Hello World”。但问题是当我这样做时,服务器发回了“Hello World”和我刚刚发布的消息。
这是示例代码:
莫斯卡服务器
var mosca = require("mosca");
var settings = {
http: {
port: 8080,
bundle: true,
static: './'
}
};
var server = new mosca.Server(settings);
server.on('clientConnected', function(client) {
console.log('client ' + client.id+ ' connect');
});
server.on('clientDisconnected', function(client) {
console.log('client ' + client.id+ ' disconnect');
});
// fired when a packet is send from server and is received from client
server.on('published', function(packet, client) {
// console.log('Published', packet);
if(typeof packet.payload == "object"){
console.log(packet);
console.log("From Client(Buffer) : "+ packet.payload.toString());
var mesFromServer = {
topic:packet.topic,
payload:"Hello World",
qos:0,
retain:false
};
server.publish(mesFromServer,client);
}
});
server.on('ready', setup);
// fired when the mqtt server is ready
function setup() {
console.log('Mosca server is up and running');
}
client.js 使用 mqtt.js
$(document).ready(function(){
$("#btnConnect").click(function(){
$("#Connect-loader").css("display","inline");
var client = mqtt.connect({ host: 'localhost', port:8080 });
client.on('connect', function () {
if(client.connected)
{
$("#Connect-loader").css("display","none");
$("#btnConnect").prop("disabled",true);
$("#btnDisconnect").prop("disabled",false);
$("#connect-notification").html("Server connected");
$("#connect-notification").css("color","green");
}
});
client.on('message', function (topic, message,packet) {
// message is Buffer
console.log(packet);
$("#txtDataFromServer").val($("#txtDataFromServer").val()+"From Server: " + message.toString()+"\n");
});
client.on('close',function(){
$("#btnConnect").prop("disabled",false);
$("#btnDisconnect").prop("disabled",true);
$("#connect-notification").html("Server disconnected");
$("#connect-notification").css("color","red");
});
$("#btnSend").click(function(){
var topic = $("#txtTopic").val();
var mess = $("#txtMessage").val();
if(topic != "" && mess !=""){
client.subscribe(topic);
client.publish(topic,mess,{qos:0,retain:false});
}
});
$("#btnDisconnect").click(function(){
client.end();
});
});
});
index.js 使用 express
var express = require("express");
var app = express();
app.use(express.static("public"));
app.use(express.static("node_modules"));
app.set("view engine","ejs");
app.set("views","./views");
var server = require("http").createServer(app);
server.listen(8000);
app.get("/",function(req,res){
res.render("home");
});
我启动服务器 mosca 和 index.js:
节点服务器.js
节点索引.js
然后我在我的网络上点击了一个按钮连接到 mosca,然后向它发送了一条消息“hello mqtt + mosca”,但它向我发送了 2 条消息。
从服务器:你好 mqtt + mosca
来自服务器:Hello World
而且我不希望结果是“你好 mqtt + mosca”。如何防止服务器将我发布给它的消息发回给我?