MQTT客户端的使用

<!doctype html>
<html lang="zh">
<head>
    <meta charset="utf-8">
    <title>subscriber.mqtt</title>
</head>
<body>
<script type="text/javascript" src="./mqtt.min.js"></script>
<script type="text/javascript">
    let server = 'mqtt://192.168.*.*:3881'; // MQTT服务器IP地址,这里的协议可以用ws或mqtt,但端口号必须为3881
    let port = 3881; // MQTT服务端口号
    let username = '********'; // 账号
    let password = '*******'; // 密码
    let topic = 'php-mqtt/client/test'; // 主题
    let clientId = 'test-subscriber-web'; // MQTT客户端ID号

    class MqttClient {
        client = null;

        constructor() {
            let options = {
                keepalive: 40,
                clean: true,
                connectTimeout: 4000,
                clientId: clientId,
                username: username,
                password: password,
                protocolId: 'MQIsdp',
                protocolVersion: 3,
                reconnectPeriod: 1000,
                connectTimeout: 10 * 1000,
            };

            this.client = mqtt.connect(server, options);

            this.client.on('connect', (connack) => {
                console.info('连接MQTT服务器成功');
                if (topic) {
                    this.client.subscribe(topic, (err) => {
                        if (!err) {
                            console.info('订阅主题(' + topic + ')成功');
                        }
                    })
                }
            });

            this.client.on('reconnect', () => {
                console.info('正在重新连接MQTT服务器');
            });

            this.client.on('close', function (error) {
                if (error) {
                    console.error(error)
                } else {
                    console.info('客户端已断开连接');
                }

            });

            this.client.on('offline', function () {
                console.info('offline事件触发');
            });

            //当客户端无法连接或出现错误时触发
            this.client.on('error', (error) => {
                console.error('客户端出现错误:' + error);
            });

            this.client.on('packetsend', (packet) => {
                if (packet && packet.payload) {
                    console.info('客户端已发出数据包:' + packet.payload);
                }
            });
        }

        // 断开链接
        disconnect() {
            try {
                if (this.client && this.client.connected) {
                    this.client.end();
                }
            } catch (error) {
                console.error(error);
            }
        }

        // 重新链接
        reconnect() {
            this.client.reconnect()
        }

        // 关闭
        close() {
            try {
                if (this.client && this.client.connected) {
                    this.client.end();
                    this.client = null;
                }
            } catch (error) {
                console.error(error)
            }
        }

        // 发布消息
        publish(topic, message) {
            if (this.client && this.client.connected) {
                this.client.publish(topic, message, {qos: 0, retain: true}, (error) => {
                    if (error) {
                        console.error(error);
                    } else {
                        console.info('发布消息成功');
                    }
                })
            }
        }

        // 订阅主题
        subscribe(topic) {
            if (this.client && this.client.connected) {
                this.client.subscribe(topic, {qos: 0}, function (error, granted) {
                    if (error) {
                        console.error(error);
                    } else {
                        console.info(`${granted[0].topic} 订阅成功`);
                    }
                })
            }
        }

        // 取消订阅
        unsubscribe(topic) {
            if (this.client && this.client.connected) {
                this.client.unsubscribe(topic, (error) => {
                    if (error) {
                        console.error(error);
                    } else {
                        console.info('取消订阅成功');
                    }
                })
            }
        }
    }

    let mqttClient = new MqttClient();

    // 收到消息回调
    mqttClient.client.on('message', (topic, message, packet) => {
        console.info('---------- [SUBSCRIBER] ----------');
        console.info('$topic            => ' + topic);
        console.info('$message          => ' + message.toString());
        console.info(packet);
    })

    // 断开连接回调
    mqttClient.client.on('close', function (error) {
        if (!error) {
            console.info('已断开连接');
        }
    });
</script>
</body>
</html>

Copyright © 2024 码农人生. All Rights Reserved