Vue项目实现WebSocket心跳和重连

<template>
    <div class="home">
        <h1>WebSocket服务</h1>
        <button @click="send">发送消息</button>
    </div>
</template>

<script>


export default {
    name: 'Home',
    data() {
        return {
            ws: null,
            lockReconnect: false, //是否真正建立连接
            reconnectTimer: null, //断开 重连倒计时
            startHeartTimer: null, //60s固定发送心跳定时器
            serverTimeoutObj: null
        };
    },
    created() {
        this.connect();
    },
    methods: {
        // ws连接
        connect() {
            this.ws = new WebSocket('ws:127.0.0.1:8080');
            // 监听连接开启,
            this.ws.addEventListener('open', () => {
                //开启心跳
                this.startHeart();
            });
            this.ws.addEventListener('message', (e) => {
                // 收到服务器信息,心跳重置,上报
                console.log('message', e.data);
                this.startHeart();
            });
            this.ws.addEventListener('error', (e) => {
                //重连
                console.log('error', e);
                this.reconnect();
            });
            this.ws.addEventListener('close', (e) => {
                //重连
                console.log('close', e);
                this.reconnect();
            });
        },
        //重新连接  3000-5000之间,设置延迟避免请求过多
        reconnect() {
            //设置lockReconnect变量避免重复连接
            if (this.lockReconnect) return;
            this.lockReconnect = true;
            this.reconnectTimer && clearTimeout(this.reconnectTimer);
            this.reconnectTimer = setTimeout(() => {
                this.connect();
                this.lockReconnect = false;
            }, parseInt(Math.random() * 2000 + 3000));
        },
        //重置心跳
        reset() {
            clearTimeout(this.serverTimeoutObj);
            clearTimeout(this.startHeartTimer);
        },
        // 60s固定发送心跳
        startHeart() {
            this.reset();
            this.startHeartTimer = setTimeout(() => {
                //这里发送一个心跳,后端收到后,返回一个心跳消息,
                //onmessage拿到返回的心跳就说明连接正常
                this.ws.send({
                    cmd: 1100
                });
                //如果超过一定时间还没重置,说明后端主动断开了
                self.serverTimeoutObj = setTimeout(() => {
                    //如果onclose会执行reconnect,我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
                    this.ws.close();
                }, 60000);
            }, 60000);
        },
        send() {
            this.ws.send(JSON.stringify({ name: '发送信息到服务器' }));
        }
    }
};
</script>

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue实现WebSocket心跳机制可以通过以下步骤进行: 1. 首先,安装WebSocket库。可以使用npm或yarn来安装,例如:`npm install vue-native-websocket`。 2. 在Vue组件中引入WebSocket库,并创建WebSocket实例。可以在Vue组件的`created`或`mounted`生命周期钩子函数中创建WebSocket实例。例如: ```javascript import VueNativeSock from 'vue-native-websocket'; export default { created() { Vue.use(VueNativeSock, 'ws://localhost:8080', { reconnection: true, // 是否自动重连 reconnectionAttempts: 5, // 重连尝试次数 reconnectionDelay: 3000, // 重连延迟时间(毫秒) format: 'json', // 数据格式 }); }, }; ``` 3. 添加心跳机制。可以使用Vue的定时器函数`setInterval`来定时发送心跳包。例如: ```javascript export default { created() { // 创建WebSocket实例 Vue.use(VueNativeSock, 'ws://localhost:8080', { reconnection: true, reconnectionAttempts: 5, reconnectionDelay: 3000, format: 'json', }); // 发送心跳包 setInterval(() => { this.$socket.sendObj({ type: 'heartbeat' }); }, 5000); // 每隔5秒发送一次心跳包 }, }; ``` 4. 监听心跳回复。在Vue组件中监听WebSocket的消息事件,当接收到心跳回复时,可以根据需要进行相应的处理。例如: ```javascript export default { created() { // 创建WebSocket实例 Vue.use(VueNativeSock, 'ws://localhost:8080', { reconnection: true, reconnectionAttempts: 5, reconnectionDelay: 3000, format: 'json', }); // 发送心跳包 setInterval(() => { this.$socket.sendObj({ type: 'heartbeat' }); }, 5000); // 监听WebSocket消息事件 this.$socket.onMessage((message) => { const data = JSON.parse(message.data); if (data.type === 'heartbeat_reply') { // 处理心跳回复 console.log('Received heartbeat reply'); } }); }, }; ``` 这样,你就可以在Vue实现WebSocket心跳机制了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值