Web瀏覽器端經過https 使用mqtt通信

作的產品簡介

此次須要作一個web端的上課平臺,有音視頻通信,有白板(畫板)功能,有文字通信等。
技術點javascript

  1. 音視頻通信須要走Webrtcjava

  2. 須要跟ios, android, windows, mac 客戶端互聯互通node

  3. 通常通信經過mqtt協議android

MQTT簡介

MQTT(Message Queuing Telemetry Transport,消息隊列遙測傳輸)是IBM開發的一個即時通信協議,有可能成爲物聯網的重要組成部分。該協議支持全部平臺,幾乎能夠把全部聯網物品和外部鏈接起來,被用來當作傳感器和制動器(好比經過Twitter讓房屋聯網)的通訊協議。ios

MQTT組成

1 Broker (server端)
有EMQ、Mosquitto、 HiveMQ等等,此次公司採用的是EMQgit

2 Client(web client端)github

mqtt.js https://github.com/mqttjs/MQT...
Eclipse Paho Client https://eclipse.org/paho/clie...web

通過實際測驗比較 Eclipse Paho的庫比較好用windows

MQTT遇到的坑

mqtt經過http通信還算是比較簡單的,大概經過例子一個小時就能夠掌握了。因爲我作的項目有音視頻須要webrtc,
而webrtc是必需要經過https才能通訊的,So 全部的鏈接都必需要經過ssl加密了。可是mqtt在https下面通信一直報錯,鏈接不上,解決的過程比較波折服務器

解決過程

1 部署本地https證書 (https在本地服務器環境中的部署)
經過openssl建立ssl證書
經過node.js 引入證書,代碼以下

const https = require('https');

const options = {
    key: fs.readFileSync('./cert/key.pem'),
    cert: fs.readFileSync('./cert/cert.pem'),
    rejectUnauthorized: true
};

let httpserver = https.createServer(options, app);

httpserver.listen(3002, function () {
    console.log('Https server listening on port ' + 3002);
});

部署完了以後,仍是通信失敗。 想到了經過https 須要https的資源

2 部署mqtt Broker(服務端)

一開始本身使用了開源的Mosquitto測試,發現很難部署https環境,後來仍是直接使用了EMQ,EMQ自然支持了。
文檔中也說明了端口,IOS 安卓等客戶端能夠直接使用 1883端口,可是web是經過 8083和 8084端口進行通信的。
圖片描述

在公司運維大神的成功協助下,配置好了 EMQ的https環境

我想這下應該好了吧,而後興奮的用 mqtt.js 鏈接,結果仍是報錯了 :-(

3 更換mqtt client 類庫
使用了Eclipse Paho Client,終於,終於,成功了
代碼以下

const mqttHost = 'm.landi.com';
    const mqttPort = 8084;
    const mqttuseSSL = true;
    
    // Create a client instance
    mqttClient = new Paho.MQTT.Client(mqttHost, Number(mqttPort), this.mqttClientID);

    // connect the client
    mqttClient.connect({onSuccess: onConnect, useSSL: mqttuseSSL});

最後,經過ios等客戶端過來的消息順利的實時抵達,在白板上畫線等各類操做實現就很容易了。

圖片描述

相關文章
相關標籤/搜索