結合mqtt的websocket的連接過程

Websocket是一種用於H5瀏覽器的實時通訊協議,可以做到數據的實時推送,可適用於廣泛的工作環境,例如客服系統、物聯網數據傳輸系統,該測試工具可用於websocket開發初期的測試工作。

//訂閱
subScribe() {
    let _this = this;
    var xhr = new XMLHttpRequest();
    xhr.open('GET', "http://192.168.0.102:8033...");
    xhr.send(null);
    xhr.onreadystatechange = function () {
        if (xhr.status === 200 && xhr.readyState === 4) {
            _this.initWebSocket();
        }
    }
},
//初始化websocket
initWebSocket() {
    if ('WebSocket' in window) {
        const hsurl = "ws://192.168.0.102:8033...."
        this.websocket = new WebSocket(hsurl);
        this.websocket.onopen = this.websocketonopen;
        this.websocket.onerror = this.websocketonerror;
        this.websocket.onmessage = this.websocketonmessage;
        this.websocket.onclose = this.websocketonclose;
    } else {
        return this.$message({
            message: "當前瀏覽器不支持WebSocket",
            type: "erroe",
            duration: 1000
        })
    }
},
websocketonopen() {
    console.log("WebSocket連接成功");
    //發送請求,向websocket請求數據
},

websocketonerror(e) {
    //錯誤
    console.log("WebSocket連接發生錯誤");
},

websocketonmessage(e) {
    let _this = this;
    console.log(e);
    //數據接收
    //處理器handler
    let receiveData = e.data;
    console.log(receiveData);
    if (receiveData != "連接成功") {
       //該做什麼
        }
    }
},

websocketonclose(e) {
    //關閉
    console.log("斷開連接", e);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章