process.env.VUE_APP_WS_URL是vue3中开发环境中的websocket地址
核心代码
data() {
return {
// 重试定时器
wsIn: null,
// websocket
ws: null,
id: null
};
},
mounted() {
this.webSockectInitMessage(
process.env.VUE_APP_WS_URL + '/websocket/' + this.id
);
},
methods: {
//连接websocket
webSockectInitMessage(wsurl) {
if ('WebSocket' in window) {
console.log('您的浏览器支持 WebSocket!');
//创建一个websocket
this.ws = new WebSocket(wsurl);
//连接成功后的回调函数
this.ws.onopen = function () {
console.log('WebSocket Open...');
if (this.wsIn) {
clearInterval(this.wsIn);
}
};
//收到返回数据后的回调函数
this.ws.onmessage = (evt) => {
let data = JSON.parse(evt.data);
console.log(data) //推送过来的数据
};
//连接关闭后的回调函数
this.ws.onclose = function () {
console.log('WebSocket close...');
};
//连接失败重试
this.ws.onerror = () => {
this.wsIn = setTimeout(() => {
this.ws.close();
this.webSockectInitMessage(wsurl);
}, 3000);
};
} else {
// 浏览器不支持 WebSocket
alert('您的浏览器不支持 WebSocket!');
}
},
}
各位客官要是感觉有用的话能留个小心心嘛,谢谢啦!!!^ v ^