話不多說,直接上代碼吧
<script>
export default {
name: "indexPage",
props: {},
components: {},
data() {
return {
websock: null, //websocket物件
maxReconnect: 5, //最大重連次數
wsUrl: "ws://192.168.1.1",
};
},
methods: {
/**
* 監聽方法
*/
// 初始化webSocket
initWebSocket() {
if (typeof WebSocket === "undefined") {
alert("您的瀏覽器不支持WebSocket");
return false;
}
console.log("初始化連接websocket");
this.websock = new WebSocket(this.wsUrl);
//連接成功
this.websock.onopen = this.websocketonopen;
//接收后端回傳的資料
this.websock.onmessage = this.websocketonmessage;
//連接錯誤觸發
this.websock.onerror = this.websocketonerror;
//斷開連接觸發
this.websock.onclose = this.websocketclose;
},
//連接成功
websocketonopen() {
console.log("WebSocket連接成功");
// 判斷是否在正常連接狀態
if (this.websock.readyState === 1) {
// 發送訊息
this.websockSend("1001");
}
},
//接收后端回傳的資料
websocketonmessage(e) {
let dataJson = JSON.parse(e.data);
},
//連接錯誤觸發
websocketonerror(e) {
console.log(`連接發生錯誤的資訊:`, e);
// this.reconnect();
// 其實可以不在這重連,因為發生錯誤后會自動斷開連接,可能會導致觸發兩次重連
},
//斷開連接觸發
websocketclose(e) {
console.log("斷開連接", e);
this.reconnect();
},
// 嘗試重連
reconnect() {
console.log("嘗試重連");
setTimeout(() => {
// this.maxReconnect-- // 不做限制 連不上一直重連
this.initWebSocket();
}, 60 * 1000);
},
/**
* 請求資料
*/
//websock請求
websockSend(command) {
// 把后臺需要的引數資料傳過去
let params = {};
params.data = {
command,
};
//發給后端的資料需要字串化
this.websock.send(JSON.stringify(params));
},
},
mounted() {
this.initWebSocket();
},
computed: {},
watch: {},
filters: {},
beforeDestroy() {
//頁面銷毀時關閉ws連接
if (this.websock) {
this.websock.close(); // 關閉websocket
}
},
};
</script>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/290408.html
標籤:其他
