当新客户端连接和断开连接时,有什么方法可以接收事件吗?

Is there any way to receive event when new client connect and disconnect?

我们使用 node 作为服务器,使用 mqtt 作为库。

我们安装了 mosquitto 作为网络套接字的代理程序。

现在我们必须跟踪新客户端连接和断开连接的记录,但问题是我们无法获取任何事件。

那么有什么办法可以实现这个吗?

const mqttServer = require('mqtt');

const clientId = appName + "_" + moment().valueOf();
const conOptions = {
    clientId,
    username: mqtt.user,
    password: mqtt.pass,
    keepalive: 10,
    clean: false,
    rejectUnauthorized: false
};

const conUrl = mqtt.uri;
const mqttClient = mqttServer.connect(conUrl, conOptions);

mqttClient.on("error", (err) => {
    logger.error(`${chalk.red('✗')} MQTT Error : `, err);
});

mqttClient.on('offline', () => {
    logger.error(`${chalk.red('✗')} MQTT Offline`);
});

mqttClient.on('reconnect', () => {
    logger.error(`${chalk.red('✗')} MQTT Reconnect`);
});

mqttClient.on('connect', () => {
    logger.info(`${chalk.green('✓')} MQTT Connected with ClientID ${chalk.yellow(clientId)}`);
});

mqttClient.on('message', (topic, message) => {
    logger.error(`New message in MQTT : ${message.toString()} on ${topic}`);
});

为什么不让每个客户端在 connect/disconnect 时发布自己的消息。

这使您可以准确控制邮件中的内容。

您可以在告诉客户端断开连接之前发送断开连接消息。

此外,如果由于 crash/network 故障而断开连接,您还可以使用 Last Will & Testament 让代理发布(在 KeepAlive 过期后)代表客户端的消息。

此技术适用于任何浏览器。