如果在MQTT中断开一个客户端,如何将断开连接消息发送到订阅的客户端?

时间:2017-06-03 09:28:57

标签: node.js mqtt broker

我尝试了客户端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");
});

1 个答案:

答案 0 :(得分:0)

你在这里问的不完全清楚,但是:

  1. 使用MQTT,您无法知道哪些客户订阅了哪些主题
  2. 无法知道邮件是否已发送给特定客户
  3. 您可以构建一个系统来确定客户端是否可能在线。你需要使用遗嘱和遗嘱(LWT)功能。

    • 当您的客户端连接时,它会将保留的消息发布到给定主题(例如client1 / online payload:1)
    • 如果客户端由于崩溃/网络故障而脱机,则将LWT设置为将有效负载0发布到同一主题
    • 当您干净地关闭客户端时,您需要手动向主题发布0,因为LWT只会在发生故障时触发。