VUE項目開發中使用WebSocket



初始化WebSocket
initWebSocket(){ //初始化weosocket
const wsuri = 'ws://10.100.45.8:8888/websocket';//ws地址
this.websock = new WebSocket(wsuri);
this.websock.onopen = this.websocketonopen;
this.websock.onerror = this.websocketonerror;
this.websock.onmessage = this.websocketonmessage;
this.websock.onclose = this.websocketclose;
// this.websock.addEventListener('open', function () { //監聽
// });

},

打開WebSocket
websocketonopen(e) {
let code = 4;
this.websock.send(code);// 連接完成后向后端發送信息
},

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

接收后端返回的數據
websocketonmessage(e){ //數據接收
let data = JSON.parse(e.data);
console.log(data)
},

關閉WebSocket,一般在頁面關閉時關閉,VUE提供了destroyed方法可以再頁面銷毀時調用websocketclose。
websocketclose(e){ //關閉
this.websock.close();

},

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM