话不多说直接上代码
export default class websocketClass {
url= ''
socketTask= null
isDisconnect= true
heartbeatTimer= null
heartbeatInterval= 3000
onMessage= () => {}
constructor (data) {
this.url = data.url || this.url
this.onMessage = data?.onMessage?.bind(this) || this.onMessage.bind(this)
this.heartbeatInterval = data.heartbeatInterval || this.heartbeatInterval
}
connect = () => {
if (this.isDisconnect) {
this.isDisconnect = false
console.log('WebSocket连接中...', this.url)
console.log('socketTask', this.socketTask)
this.socketTask = new WebSocket(this.url)
this.socketTask.onopen = () => {
console.log('WebSocket连接已打开')
this.startHeartbeat()
}
this.socketTask.onclose = () => {
console.log('WebSocket连接已关闭')
if (this.isDisconnect) {
setTimeout(() => {
console.log('WebSocket尝试重新连接')
this.connect()
}, 1000)
}
}
this.socketTask.onerror = (error) => {
console.error('WebSocket连接发生错误:', error)
this.isDisconnect = true
}
this.socketTask.onmessage = (res) => {
let data = JSON.parse(res.data)
console.log('收到服务器消息:', data)
this.onMessage && this.onMessage(data)
}
}
}
disconnect = () => {
console.log('主动断开')
if (this.socketTask) {
this.isDisconnect = false
this.socketTask.close()
this.stopHeartbeat()
this.socketTask = null
}
}
startHeartbeat = () => {
this.heartbeatTimer = setInterval(() => {
if (this.socketTask) {
console.log('发送心跳')
this.sendMessage({})
}
}, this.heartbeatInterval)
}
stopHeartbeat = () => {
clearInterval(this.heartbeatTimer)
}
sendMessage = (message) => {
console.log('发送消息:sendMessage', message)
if (this.socketTask) {
this.socketTask.send({
data: JSON.stringify(message),
})
}
}
}