【问题标题】:How can I send the disconnect messages to subscribed clients if one client is disconnected in MQTT?如果一个客户端在 MQTT 中断开连接,我如何向订阅的客户端发送断开连接消息?
【发布时间】:2017-11-04 15:54:17
【问题描述】:

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

【问题讨论】:

标签: node.js mqtt broker


【解决方案1】:

这里并不完全清楚你在问什么,但是:

  1. 使用 MQTT,您无法知道哪些客户端订阅了哪些主题
  2. 无法知道消息是否已发送到特定客户端

您可以构建一个系统来确定客户是否可能在线。您需要使用遗嘱和遗嘱 (LWT) 功能。

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

【讨论】:

  • 谢谢您的评论。我的问题是client1订阅了client2的所有主题。如果我关闭client1程序。我想向client2程序发送消息。 “client1 is disconnected”,因为我在 client1 中订阅了 client2 主题。这可能与否。
  • 我认为 LWT 示例就是这样做的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多