封装
export function NewWebSocket () {
this.websocket = null
this.heartbeat_timer = null
this.active_close = null
this.init = (params) => {
this.websocket = new WebSocket(params.url)
this.websocket.onopen = (data) => {
this.heartbeat()
if (params.onopen) {
params.onopen('webSocket已连接', data)
}
}
this.websocket.onmessage = (data) => {
if (params.onmessage) {
let obj=JSON.parse(data.data)
// console.log('onmessage', obj)
if (obj&&obj.type&&obj.type=='ping'){
return
}
params.onmessage(data)
}
}
this.websocket.onclose = () => {
clearInterval(this.heartbeat_timer)
if (this.active_close) {
if (params.onclose) {
params.onclose('连接已手动关闭')
}
} else {
this.reconnect(params)
if (params.onclose) {
params.onclose('连接已关闭, 正在重连')
}
}
}
this.websocket.onerror = () => {
clearInterval(this.heartbeat_timer)
if (params.onerror) {
params.message('连接发生错误!等待五秒后重连')
setTimeout(() => {
this.reconnect(params)
},5000)
}
}
}
this.heartbeat = () => {
console.log('执行心跳')
if (this.heartbeat_timer) {
clearInterval(this.heartbeat_timer)
}
this.heartbeat_timer = setInterval(() =>{
this.websocket.send(
JSON.stringify({
type: 'ping'
})
)
},10000)
}
this.reconnect = (params) => {
console.log('执行重连')
this.active_close = false
if (this.websocket) {
this.websocket.close()
}
this.init(params)
}
this.close = () => {
console.log('手动关闭,无需重连')
clearInterval(this.heartbeat_timer)
this.active_close = true
this.websocket.close()
}
}
调用
import {NewWebSocket} from '@/utils/messageWebscoket'
this.socket = new NewWebSocket()
this.socket.init({
url: `xxxxxx`, // 自己的ws 地址
onopen: (msg, data) => {
console.log(msg, data)
},
onmessage: (res) => {
console.log('scoket消息', res)
},
onclose: (data) => {
console.log(data)
}
})