这套代码目前个人在项目中已使用,大家可以直接拿去使用,相关注意点已在代码中注释,方便大家阅读。
核心代码:
//这里需要引入vuex
import store from './store';
let wsConnection = {
$ws: null,
lockReturn: false,
timeout: 60 * 1000 * 5,
timeoutObj: null,
timeoutNum: null,
serverTimeoutObj: null,
//初始化webSocket长连接
initWebSocket: function () {
let corpId = localStorage.getItem('corpId');
let name = localStorage.getItem('username');
this.$ws = new WebSocket(wsurl);//写入地址 这里的地址可以在initWebSocket方法加入参数
this.$ws.onopen = this.wsOpen;
this.$ws.onclose = this.wsClose;
this.$ws.onmessage = this.wsMsg;
this.$ws.onerror = this.wsError;
},
//打开websocket
wsOpen: function (e) {
//开始websocket心跳
wsConnection.startWs