我尝试了客户端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");
});
答案 0 :(得分:0)
你在这里问的不完全清楚,但是:
您可以构建一个系统来确定客户端是否可能在线。你需要使用遗嘱和遗嘱(LWT)功能。