# 網路不穩?QoS 網路服務品質 --- ## 回顧 上上次的MQTT [通訊協定 MQTT之淺入~~深~~出](https://hackmd.io/@fan9704/rJ9hUhpRi) ---- ## 物聯網 Internet Of Thing ![](https://i.imgur.com/vTykwCt.png) ---- ### 當訊息是很重要的不可遺失的呢? > 例如前途的瓦斯爐訊號 ---- ### 遺失1 Pub -> Broker ![](https://i.imgur.com/vfXbAQX.png) ---- ### 遺失2 Broker -> Sub ![](https://i.imgur.com/fKy1tax.png) ---- ### 額外補充 遺失3 Broker -> Storage(AMQP協議中才有) ![](https://i.imgur.com/9tAPH8Y.png) [補充資料AMQP Transaction機制](https://medium.com/willhanchen/rabbitmq-%E5%A6%82%E4%BD%95%E4%BF%9D%E8%AD%89%E6%B6%88%E6%81%AF%E5%8F%AF%E9%9D%A0%E6%80%A7-398cb9d2836b) --- ## 解決方案 QoS Quality of Service(網路服務品質) 在MQTT中是用來設置訊息傳輸的規則 ---- ### QoS 0 > 最多一次(不管有沒有送到就是送一次) ---- ![](https://i.imgur.com/mbdLOtZ.png) ---- ### QoS 1 > 最少一次(類似郵件掛號,必須被確認packetId封包ID) 過一段時間都沒收到確認會補送訊息 ---- ![](https://i.imgur.com/cGKZfnN.png) ---- ### QoS 2 > 確認一次(避免重複丟出訊息) ---- ![](https://i.imgur.com/0yMyrMD.png) --- ## 實作環節 ---- ### 新增帶有QoS等級的發送訊息方法 ```typescript= import express from 'express'; import mqtt, { QoS } from 'mqtt'; const app = express(); const mqttClient = mqtt.connect('mqtt://localhost'); app.get('/publish', (req, res) => { const message = req.query.message as string; const qosLevel = parseInt(req.query.qos as string); if (![0, 1, 2].includes(qosLevel)) { res.status(400).send('Invalid QoS level'); return; } mqttClient.publish('topic', message, { qos: qosLevel as QoS }, (err) => { if (err) { console.error(`Error publishing message: ${err}`); res.status(500).send('Error publishing message'); return; } console.log(`Published message "${message}" with QoS ${qosLevel}`); res.status(200).send('Message published'); }); }); app.listen(3000, () => { console.log('Express server started on port 3000'); }); ``` ---- ### 去處理QoS 訊息 ```typescript= import express from 'express'; import mqtt, { QoS } from 'mqtt'; const app = express(); const mqttClient = mqtt.connect('mqtt://localhost'); mqttClient.on('connect', () => { mqttClient.subscribe('topic', { qos: 2 }, (err) => { if (err) { console.error(`Error subscribing to topic: ${err}`); } else { console.log('Subscribed to topic with QoS 2'); } }); }); mqttClient.on('message', (topic, message, packet) => { console.log(`Received message "${message.toString()}" on topic "${topic}" with QoS ${packet.qos}`); }); app.listen(3000, () => { console.log('Express server started on port 3000'); }); ``` ---- [參考文章](https://swf.com.tw/?p=1015)
{"metaMigratedAt":"2023-06-17T18:56:47.909Z","metaMigratedFrom":"YAML","breaks":true,"title":"網路不穩?QoS 網路服務品質","contributors":"[{\"id\":\"4c8f8799-9dcd-430b-b7bc-8a5156d39d0b\",\"add\":7987,\"del\":5418}]"}
    59 views