我尝试了客户端1和客户端2程序,我可以轻松地与它们通信。我可以轻松发送消息并与他们接收消息,但是我不知道是否断开了一个客户的联系,我如何将断开的消息发送给订阅的客户。
客户端1:
var mqtt=require("mqtt");
var express=require("express");
var app=express();
var options={
keepalive:100,
port: 1883,
clientId:'1',
clientSession:false,
host: "http://localhost:8000",
will:
{
topic:'willMag',
payload:"connection closed abnormallly r",
qos:1,
retain:true
}
};
var client=mqtt.connect("tcp://192.168.43.137:1883",options);
client.on("connect",function()
{
setInterval(function()
{
client.publish("ranjith/princy","hello love you princy",function()
{
console.log("message published in client1");
});
},2000);
client.subscribe("bv/nivi");
client.on("message",function(topic,message)
{
console.log("I recieved the topic:"+topic);
console.log("I recieved the message:"+message);
});
});
client.on("disconnect",function()
{
console.log("disconnected client1");
});
app.listen(8000,function()
{
console.log("server listen at port 8000");
});
客户端2:
var mqtt=require("mqtt");
var express=require("express");
var app=express();
var options={
keepalive:100,
port: 1883,
clientId:'2',
clientSession:false,
host: "http://localhost:8086",
will:
{
topic:'willMag',
payload:"connection closed abnormallly b",
qos:1,
retain:true
}
};
var client=mqtt.connect("tcp://192.168.43.137:1883",options);
client.on("connect",function()
{
setInterval(function(){
client.publish("bv/nivi","hello love you nivi",function()
{
console.log("message published in client2");
});
},2000);
client.subscribe("ranjith/princy");
client.on("message",function(topic,message)
{
console.log("I recieved the topic:"+topic);
console.log("I recieved the message:"+message);
});
});
client.on("disconnect",function()
{
console.log("disconnected client2");
});
app.listen(8086,function()
{
console.log("server listen at port 8000");
});
尚不完全清楚您在这里问什么,但是:
- 使用MQTT,您不知道客户订阅了哪些主题
- 没有办法知道是否已将消息传递给特定的客户
您可以构建一个系统来确定客户端是否可能在线。您需要使用最后的遗嘱和遗嘱(LWT(功能。
- 当您的客户连接时,它将保留的消息发布到给定主题(例如客户端/在线有效载荷:1(
- 您将LWT设置为如果客户崩溃/网络失败 ,则将有效载荷0发布到同一主题
- 当您干净地关闭客户时,您需要手动将0发布到主题,因为LWT仅在发生故障时会发射。