WebSocket接收后台实时消息推送 加入心跳包机制_谢大源

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/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值