websocket-hearbeat-js心跳检测,vuex封装,即时通信,前后端互通消息

简介:

websocket-heartbeat-js基于浏览器js原生websocket。可以定时发送socket请求,具有心跳检测以及自动重连机制。网络断开或者服务端问题造成连接断开,socket会自动重连,直至连接成功。只有客户端主动断开连接,才会终止socket自动连接。

下载:

npm i websocket-heartbeat-js -S

注册socket:

// modules/websocketHearbeat.js文件
import webscoketHeartbeatJs from "websocket-heartbeat-js";
const state = {
    socketJs: null,
}

const mutations = {
    saveSocketMutations(state, socket) {
        state.socketJs = socket;
    }
}

const actions = {
    setInitSocket({ commit }, params) {
        let {
            from = '',
            callback = () => { },
        } = params;
        console.log('创建socket实例');
        let socket = new webscoketHeartbeatJs({
            url: 'ws://xxxxxxxx', // ws:// + 域名/后端本地服务 + 拼接路径/参数(根据实际情况修改)
        })
        socket.open = () => {
            console.log('已建立连接...');
            socket.send('heartbeat'); // 发送消息给后端
        }

        socket.onmessasge = (event) => {
            console.log('接收...', event);
            // 服务端主动断开连接
            if (event.data == 'colse') {
                socket.colse(); // 关闭连接
                return;
            }
            let message = JSON.parse(event.data);
            if (from == 'App.vue') {
                callback && callback(message);
            }
        }

        socket.onreconnect = () => {
            console.log('onreconnect...');
        }

        socket.onerror = () => {
            console.log('onerror...');
        }

        socket.onclose = () => {
            console.log('取消连接...');
        }

        commit('saveSocketMutations', socket);
    }
}

export default {
    state,
    mutations,
    actions,
}

vuex:

// store/index.js文件
import Vue from 'vue'
import Vuex from 'vuex'
import getters from "./getter.js";
import WebsocketHearbeat from "./modules/websocketHearbeat.js";

Vue.use(Vuex)

export default new Vuex.Store({
  getters,
  modules: {
    WebsocketHearbeat,
  }
})

getter.js:

// store/getter.js
const getters = {
    socketJs: state => state.webscoketHearbeat.socketJs,
}

export default getters;

使用:

this.$store.dispatch('setInitSocket', {
    from: 'App.vue',
    callBack: (msg) => {
        // 接收到消息后的处理逻辑
        console.log('msg--', msg);
    },
})

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

&做梦的少年&

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值