-
判斷當前瀏覽器是否支持websocket
-
創建websocket實體
new WebSocket(url,protocols)
url: 地址(必傳)
protocols: 用于定義子協議(非必傳),需前后端約定好,用來處理不同資料型別,陣列或者字串,不傳默認空字串
注意:url的協議識別符號是ws、wss,沒有同源限制 -
在組件加載時連接、組件銷毀時關閉
-
常用事件
- open 連接成功后的回呼函式
此例中 this.websocket.onopen = function(){} - message 當收到服務器的回傳時的回呼函式
此例中 this.websocket.onmessage = function(){} - error 連接失敗時的回呼函式
此例中 this.websocket.onerror = function(){} - close 連接關閉時的回呼函式
此例中 this.websocket.onclose = function(){}
注意:也可通過addEventListener()監聽事件,如this.websocket.addEventListener(‘open’,function(){})
- 常用方法
- close 斷開連接
此例中 this.websocket.close() - send 傳輸至服務器的資料(必須處于open狀態)
此例中 this.websocket.send()
- 常用屬性
- protocol 回傳服務器端選中的子協議的名字(即在new WebSocket(url,protocols)時的protocols)
此例中 console.log(this.websocket.protocol) - readyState 回傳連接狀態(正在鏈接–0、已經連接–1、正在關閉–2、已經關閉–3)
此例中 console.log(this.websocket.readyState) - url 回傳url絕對路徑(即在new WebSocket(url,protocols)時的url絕對路徑)
此例中 console.log(this.websocket.url)
- 代碼
<template>
<div></div>
</template>
<script>
export default {
data() {
return {
websocket: "",
};
},
methods: {
// 創建websocket實體
websocketCreate() {
let url = "ws://127.0.0.1:3000/test-get.json";
this.websocket = new WebSocket(url);
this.websocket.onopen = this.websocketOpen;
this.websocket.onmessage = this.websocketMessage;
this.websocket.onerror = this.websocketError;
this.websocket.onclose = this.websocketClose;
},
websocketOpen() {
console.log("連接建立open");
},
websocketError() {
//連接失敗的時候重連
this.websocketCreate();
console.log("失敗error");
},
websocketMessage() {
console.log("資料接收message");
},
websocketClose() {
console.log("斷開連接close");
},
},
// 組件加載時連接
mounted() {
// 判斷當前瀏覽器是否支持websocket
if (!!window.WebSocket && window.WebSocket.prototype.send) {
this.websocketCreate();
} else {
console.log("當前瀏覽器不支持websocket");
}
},
// 組件銷毀時關閉
destroyed() {
this.websocket.close();
},
};
</script>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/241026.html
標籤:其他
下一篇:關于字串的那點事兒(一)
