WebSocket接收后台实时消息推送 加入心跳包机制,避免自动断开连接!
跳转typescript + vue3 实现websocket+心跳机制写入 纯代码记录
记录记录
完整 上码.
let ws = null,
timeout1 = null, //心跳定时器
timeout2 = null,//断开重新连接定时器
timeout3 = null,// 重连失败断开连接定时器
isTrue = false //判断是否需要重连
//保存暴露出的方法接收的参数
let self = null,
connectUrl = '',
methods = null
function socketConnect(_this,url,method) {
let wsUrl = url ? url : "默认连接地址"
if(!method) method = {}
self = _this
connectUrl = url
methods = method
//创建webSocket实例化
ws = new WebSocket(wsUrl);
//用于指定连接成功后的回调函数 打开监听
ws.onopen = method.onopen ? method.onopen : function (event) {
console.log("webSocket连接成功 ...");
start()
// ws.send("Hello WebSockets!");
}
//用于指定收到服务器数据后的回调函数 ws.binaryType指定接收数据
ws.onmessage =function (event) {
// console.log("收到服务器数据: " + event.data);
if(method.onmessage){
method.onmessage(event)
}
reset()
}
//用于指定连接关闭后的回调函数 关闭监听
ws.onclose = method.onclose ? method.onclose : function (event) {
console.log("连接关闭.");
// reconnect()
}
ws.onerror = method.onerror ? method.onerror : function () {
console.log('连接错误')
reconnect()
}
// 组件销毁时调用,中断websocket链接
_this.socketclose = () => {
ws.close()
}
_this.ws = ws
}
function start(){//心跳开始
// console.log('心跳开始')
timeout1 && clearTimeout(timeout1)
timeout3 && clearTimeout(timeout3)
timeout1 = setTimeout(()=>{
//判断是否断开连接 readyState==1 连接中
if(ws.readyState==1){
ws.send('蹦蹦蹦蹦~心跳')
}else{
//重新连接
reconnect()
//重新连接超时关闭连接
timeout3 = setTimeout(()=>{
console.log('重新连接超时关闭连接')
ws.close()
},30*1000)
}
},30*1000)
}
function reconnect(){//重新连接
if(isTrue){
return
}
console.log('尝试重新连接')
isTrue = true
timeout2 && clearTimeout(timeout2)
timeout2 = setTimeout(()=>{
socketConnect(self,connectUrl,methods)
isTrue = false
},5000)
}
function reset(){//重置心跳
// console.log('重置心跳')
clearTimeout(timeout1)
clearTimeout(timeout3)
start()
}
export default {
socketConnect
}
心跳机制参考:https://blog.csdn.net/kang19980516/article/details/104658081/