vue 连接 websocket
创建 websocket.js 文件,内容如下:
在需要连接websocket的地方,引入 websocket.js,执行初始化方法
export default {
websocket: undefined,
heartbeat: undefined,
// 初始化 websocket
initWebsocket(){
// 如果之前初始化过了,不再重新初始化
if (this.websocket) {
return
}
// 如果当前浏览器不支持websocket,不初始化
if (!("WebSocket" in window)){
console.log("当前浏览器不支持 webscoket")
return;
}
// 连接 websocket
this.websocket = new WebSocket((location.protocol == "https:" ? "wss://" : "ws://") + location.host + "/请求url")
// 连接成功
this.websocket.onopen = () => {
console.log("websocket 连接成功")
}
// 收到消息
this.websocket.onmessage = (event) => {
let data = JSON.parse(event.data)
// 执行相关业务逻辑
}
// websocket 关闭时
this.websocket.onclose = () => {
console.log("websocket 已关闭,1秒后重新连接")
setTimeout(() => {
this.websocket = undefined
this.initWebsocket()
},1000)
}
// 窗口关闭时
window.onbeforeunload = () => {
if (this.websocket) {
this.websocket.close()
this.websocket = undefined
}
}
// 定时向服务器发送消息,保存连接
if (!this.heartbeat) {
this.heartbeat = setInterval(() => {
if(this.websocket){
this.websocket.send("heartbeat")
}
},50 * 1000)
};
}
}
正文到此结束