created(){
this.initWebSocket();
},
beforeDestroy() { ////關閉時斷開socket連接
this.websocketclose();
},
methods:{
initWebSocket(address) {
let userId = this.info.id;
let roomId = this.$route.query.id;
let nickname = this.info.nickname;
// WebSocket與普通的請求所用協議有所不同,ws等同於http,wss等同於https
// 測試 115.28.185.152:8082
// 正式 47.104.29.50:8081
this.websock = new WebSocket(url); //這里是websocket服務地址,這里的地址可以前端根據后台地址參數規則拼成,也可以向后端請求
this.websock.onopen = this.websocketonopen;
this.websock.onerror = this.websocketonerror;
this.websock.onmessage = this.websocketonmessage;
this.websock.onclose = this.websocketclose;
//監聽窗口關閉事件,當窗口關閉時,主動去關閉websocket連接,防止連接還沒斷開就關閉窗口,server端會拋異常。Ï
window.onbeforeunload = this.websocketclose;
},
websocketonopen() {
this.playerOptions.autoplay=true;
console.log("WebSocket連接成功");
},
websocketonerror(e) {
console.log("WebSocket連接發生錯誤");
},
websocketonmessage(e) {
let data = JSON.parse(e.data);
if (data.type !== "1") {
this.msgs.push(data);
}
},
websocketclose(e) {
this.websock.close()
console.log("connection closed ");
},}