最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

基于JavaScript的MQTT實(shí)時(shí)通信應(yīng)用開發(fā)實(shí)戰(zhàn)記錄

 更新時(shí)間:2025年09月01日 14:35:36   作者:寫段代碼給黨看  
MQTT是輕量級(jí)發(fā)布/訂閱協(xié)議,專為物聯(lián)網(wǎng)等低帶寬場(chǎng)景設(shè)計(jì),支持QoS分級(jí)、遺囑消息等特性,本文通過JavaScript庫(kù)實(shí)現(xiàn)客戶端,涵蓋連接管理、消息處理及優(yōu)化方案,適用于實(shí)時(shí)通信應(yīng)用開發(fā),本文給大家介紹基于JavaScript的MQTT實(shí)時(shí)通信應(yīng)用開發(fā),感興趣的朋友一起看看吧

MQTT 協(xié)議入門與實(shí)踐:使用 JavaScript 構(gòu)建實(shí)時(shí)通信應(yīng)用

1. 什么是 MQTT?

MQTT(Message Queuing Telemetry Transport)是一種輕量級(jí)的 發(fā)布/訂閱(Pub-Sub) 消息協(xié)議,專為低帶寬、高延遲或不穩(wěn)定的網(wǎng)絡(luò)環(huán)境設(shè)計(jì)。它廣泛應(yīng)用于物聯(lián)網(wǎng)(IoT)、即時(shí)通訊、遠(yuǎn)程監(jiān)控等場(chǎng)景。

核心特性:

  • 低開銷:協(xié)議頭部?jī)H 2 字節(jié),適合嵌入式設(shè)備。
  • 發(fā)布/訂閱模型:解耦消息生產(chǎn)者和消費(fèi)者。
  • 多 QoS 支持:提供 3 種消息傳遞質(zhì)量等級(jí)。
  • 支持遺囑消息:客戶端異常斷開時(shí)通知其他設(shè)備。

2. MQTT 基礎(chǔ)概念

術(shù)語(yǔ)說明
Broker消息代理服務(wù)器(如 Mosquitto、EMQX),負(fù)責(zé)轉(zhuǎn)發(fā)消息。
Topic消息的分類標(biāo)識(shí)(如 sensor/temperature),支持通配符 +#。
QoS消息質(zhì)量等級(jí):
0 - 最多一次(可能丟失)
1 - 至少一次(可能重復(fù))
2 - 恰好一次(可靠但開銷大)
Client發(fā)布或訂閱消息的設(shè)備或應(yīng)用。

3. 實(shí)戰(zhàn):用 JavaScript 實(shí)現(xiàn) MQTT 客戶端

以下是一個(gè)基于 mqtt.js 庫(kù)的封裝類(代碼來自提供的 mqttClient.js):

功能亮點(diǎn):

  1. 自動(dòng)重連機(jī)制
    this.client.on('reconnect', () => {
        if (++this.reconnectCount >= this.maxReconnectAttempts) {
            this.client.end(); // 超過最大重試次數(shù)后放棄
        }
    });
    
  2. Promise 封裝連接
    connect() {
        return new Promise((resolve, reject) => {
            this.client.on('connect', resolve);
            this.client.on('error', reject);
        });
    }
    
  3. 安全的資源釋放
    disconnect() {
        if (this.client?.connected) {
            this.client.end(); // 避免內(nèi)存泄漏
        }
    }
    

使用示例:

const mqttClient = new MqttClient('mqtt://broker.emqx.io');
// 連接并訂閱
mqttClient.connect().then(() => {
    mqttClient.subscribe('home/sensor', (topic, message) => {
        console.log(`[${topic}] ${message}`);
    });
    // 發(fā)布消息
    mqttClient.publish('home/light', 'ON');
});
// 頁(yè)面卸載時(shí)斷開連接
window.addEventListener('beforeunload', () => mqttClient.disconnect());

4. 常見問題與優(yōu)化建議

? 問題 1:消息重復(fù)接收

原因:QoS 1 可能導(dǎo)致重復(fù)消息。
解決:在回調(diào)函數(shù)中實(shí)現(xiàn)冪等處理(如消息 ID 去重)。

? 問題 2:連接不穩(wěn)定

優(yōu)化

  • 增加心跳檢測(cè)(keepalive 參數(shù))。
  • 使用 WebSocket 替代 TCP(適用于瀏覽器環(huán)境):
    new MqttClient('ws://broker.emqx.io:8083/mqtt');

? 安全問題

  • 避免硬編碼密碼,使用環(huán)境變量:
    new MqttClient(import.meta.env.VITE_MQTT_URL, '', '用戶名', '密碼');
    
  • 啟用 TLS 加密(mqtts://)。

5. 擴(kuò)展應(yīng)用場(chǎng)景

  • ??? 物聯(lián)網(wǎng)傳感器數(shù)據(jù)采集(如溫度上報(bào))
  • ?? 實(shí)時(shí)聊天應(yīng)用(Topic 對(duì)應(yīng)聊天室)
  • ?? 設(shè)備異常監(jiān)控(通過遺囑消息通知離線事件)

結(jié)語(yǔ)

MQTT 的輕量級(jí)和靈活性使其成為實(shí)時(shí)通信的理想選擇。通過本文的封裝類,你可以快速集成 MQTT 到你的 JavaScript 項(xiàng)目中。建議進(jìn)一步探索:

提示:在瀏覽器中使用時(shí),需注意跨域問題和 WebSocket 支持!

完整代碼示例

/**
 * 
 * 調(diào)用方式如下
 * const mqttClient = new MqttClient('mqtt://your-broker-url');
 * mqttClient.connect();
 * mqttClient.subscribe('your/topic', (topic, message) => {
 * console.log(`${topic}: ${message}`);
 * });
 * 
 * 在頁(yè)面銷毀時(shí)斷開連接,釋放資源(防止罵娘)
 * mqttClient.disconnect();
 * */
   import mqtt from 'mqtt';
// 定義MqttClient類
class MqttClient {
	// 構(gòu)造函數(shù),接收broker的URL和客戶端ID(可選)
	constructor(brokerUrl, clientId = `client-${Math.random().toString(16).substr(2, 8)}`, username = '', password = '') {
		this.brokerUrl = brokerUrl; // 存儲(chǔ)broker的URL
		this.clientId = clientId; // 存儲(chǔ)客戶端ID,如果沒有提供則生成一個(gè)隨機(jī)的
		this.client = null; // 初始化mqtt客戶端為null
		this.reconnectCount = 0; // 添加重連計(jì)數(shù)器
		this.maxReconnectAttempts = 5; // 設(shè)置最大重連次數(shù)
		this.username = username;
		this.password = password;
	}
	/**
	 * 連接到MQTT broker的方法,返回Promise
	 */
	connect() {
		return new Promise((resolve, reject) => {
			const options = {
				clientId: this.clientId,
				clean: true,
				connectTimeout: 4000,
				reconnectPeriod: 1000,
				username: this.username, // 添加用戶名配置
				password: this.password // 添加密碼配置
			};
			this.client = mqtt.connect(this.brokerUrl, options);
			this.client.on('connect', () => {
				console.log('M_connected');
				this.reconnectCount = 0; // 連接成功后重置計(jì)數(shù)器
				resolve(true);
			});
			this.client.on('error', (error) => {
				console.error('M_error:', error);
				reject(error);
			});
			this.client.on('close', () => {
				console.log('M_connection closed');
				reject(new Error('Connection closed'));
			});
			this.client.on('offline', () => {
				console.log('M_client offline');
				reject(new Error('Client offline'));
			});
			this.client.on('reconnect', () => {
				this.reconnectCount++;
				console.log(`M_reconnecting... (Attempt ${this.reconnectCount}/${this.maxReconnectAttempts})`);
				if (this.reconnectCount >= this.maxReconnectAttempts) {
					this.client.end(); // 達(dá)到最大重連次數(shù)后斷開連接
					reject(new Error('Max reconnection attempts reached'));
				}
			});
		});
	}
	/**
	 * 訂閱主題的方法,接收主題和回調(diào)函數(shù)作為參數(shù)
	 * @param {string} topic 
	 * @param {fun} callback 
	 */
	subscribe(topic, callback) {
		this.client.subscribe(topic, { qos: 1 }, (error) => { // 使用qos 1保證消息至少被傳遞一次,2 網(wǎng)絡(luò)開銷較大,不推薦用 0
			if (error) {
				console.error('Subscribe error:', error);
			} else {
				// 監(jiān)聽消息事件,當(dāng)收到消息時(shí)調(diào)用回調(diào)函數(shù),receivedTopic與訂閱主題匹配的主題
				this.client.on('message', (receivedTopic, message) => {
					callback(receivedTopic, message.toString()); // 調(diào)用回調(diào)函數(shù)處理消息
				});
			}
		});
	}
	/**
	 * 發(fā)布消息到指定主題的方法,接收主題、消息和qos(可選)作為參數(shù)
	 * @param {string} topic 
	 * @param {string|Buffer} message 
	 * @param {number} qos 
	 */
	publish(topic, message, qos = 1) {
		this.client.publish(topic, message, { qos }, (error) => { // 使用指定的qos發(fā)布消息
			if (error) {
				console.error('Publish error:', error);
			} else {
				console.log(`Published message to topic: ${topic}`);
			}
		});
	}
	/**
	 * 斷開與MQTT broker連接的方法
	 */
	disconnect() {
		// this.client.end();
		if (this.client?.connected) {
			this.client.end(); // 斷開連接
		}
	}
}
export default MqttClient;

到此這篇關(guān)于基于JavaScript的MQTT實(shí)時(shí)通信應(yīng)用開發(fā)實(shí)戰(zhàn)記錄的文章就介紹到這了,更多相關(guān)js mqtt實(shí)時(shí)通信內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

息烽县| 连山| 雅安市| 洞口县| 鹤峰县| 县级市| 娱乐| 治多县| 澄迈县| 邹城市| 垫江县| 南召县| 鄂尔多斯市| 井陉县| 紫阳县| 兖州市| 板桥市| 偃师市| 三原县| 遂川县| 静海县| 怀宁县| 麻栗坡县| 永嘉县| 盐山县| 郎溪县| 台湾省| 东港市| 肥西县| 酒泉市| 新闻| 涞源县| 灌南县| 德兴市| 五家渠市| 肃宁县| 固阳县| 霍林郭勒市| 黎平县| 隆林| 宕昌县|