<template> </template> <script> export default { data() { return{ // 用戶Id userId:'', appid:'', // 事件類型 type:'', msg:'', wsUrl:'' } }, methods: { //初始化weosocket initWebSocket() { if (typeof WebSocket === "undefined") { alert("您的瀏覽器不支持WebSocket"); return false; } const wsuri = 'ws://(后端WebSocket地址)/websocket/' + this.userId + '/' + this.appid // websocket地址 this.websock = new WebSocket(wsuri); this.websock.onopen = this.websocketonopen; this.websock.onmessage = this.websocketonmessage; this.websock.onerror = this.websocketonerror; this.websock.onclose = this.websocketclose; }, //連接成功 websocketonopen() { console.log("WebSocket連接成功"); // 添加心跳檢測,每30秒發一次數據,防止連接斷開(這跟服務器的設置有關,如果服務器沒有設置每隔多長時間不發消息斷開,可以不進行心跳設置) let self = this; this.timer = setInterval(() => { try { self.websock.send('test') console.log('發送消息'); }catch(err){ console.log('斷開了:' + err); self.connection() } }, 30000) }, //接收后端返回的數據,可以根據需要進行處理 websocketonmessage(e) { var vm = this; let data1Json = JSON.parse(e.data); console.log(data1Json); }, //連接建立失敗重連 websocketonerror(e) { console.log(`連接失敗的信息:`, e); this.initWebSocket(); // 連接失敗后嘗試重新連接 }, //關閉連接 websocketclose(e) { console.log("斷開連接", e); } }, created() { if (this.websock) { this.websock.close(); // 關閉websocket連接 } this.initWebSocket(); }, destroyed() { //頁面銷毀時關閉ws連接 if (this.websock) { this.websock.close(); // 關閉websocket } } }; </script>