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