初始化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();
},