// websock对象
let ws = null
// 心跳定时器对象
let heatInterval = null
// 心跳定时器间隔时间
const heatTimer = 5 * 1000
/**
* 初始化Socket链接
* @param {*} url
*/
function initSocket(url, callback) {
ws = new WebSocket(url)
ws.onopen = () => {
switch (ws.readyState) {
case ws.OPEN: // ws 开启状态
heartbeat()
callback('onopen', ws.readyState)
break
case ws.CONNECTING: // 正在开启状态
break
default: // 未开启
break
}
}
// 接听服务器发回的信息并处理展示
ws.onmessage = (data) => {
callback('onmessage', data)
}
// 监听连接关闭事件
ws.onclose = () => {
callback('onclose', ws.readyState)
}
// 监听并处理error事件
ws.onerror = (error) => {
callback('onerror', error)
}
}
/**
* 发送webSocket消息
* @param {*} message
*/
function sendSocket(message) {
ws.send(message)
}
/**
* 心跳监测
*/
function heartbeat() {
heatInterval = setInterval(() => {
// const sendData = { operate: 'ping' }
sendSocket('ping')
}, heatTimer)
}
/**
* 关闭连接
*/
function closeSocket() {
clearInterval(heatInterval)
ws.close()
}
export { initSocket, sendSocket, closeSocket }
使用
import { initSocket, closeSocket } from '@/utils/socket'
created() {
initSocket(`${url}`, (oper, data) => {
console.log(oper, data, 'socket')
})
}
destroyed() {
// 销毁websocket
closeSocket()
},