vue项目中websocket封装方法的使用

这套代码目前个人在项目中已使用,大家可以直接拿去使用,相关注意点已在代码中注释,方便大家阅读。

核心代码:

//这里需要引入 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.startWsHeartbeat();
 console.log('ws success')
  },
 wsClose: function (e) {
 console.log(e, 'ws close')
  },
 wsMsg: function (msg) {
 //每次接收到服务端消息后 重置 websocket 心跳
 wsConnection.resetHeartbeat();
 //服务端发送来的消息存到 vuex
store.commit('web_socket_msg', msg)
  },
 wsError: function (err) {
 console.log(err, 'ws error');
  wsConnection.reconnect()
  },
 //重启 websocket
reconnect: function () {
 let _this = this;
 if (_this.lockReturn) {
 return;
  }
 _this.lockReturn = true;
 _this.timeoutNum && clearTimeout(_this.timeoutNum);
 _this.timeoutNum = setTimeout(function () {
  _this.initWebSocket();
 _this.lockReturn = false;
 }, 3000);
  },
 startWsHeartbeat: function () {
 let _this = this;
 _this.timeoutObj && clearTimeout(_this.timeoutObj);
 _this.serverTimeoutObj && clearTimeout(_this.serverTimeoutObj);
 _this.timeoutObj = setInterval(function () {
 //判断 websocket 当前状态
if (_this.$ws.readyState != 1) {
  _this.reconnect()
  }
  }, _this.timeout);
  },
 //重置 websocket 心跳
resetHeartbeat: function () {
 let _this = this;
  clearTimeout(_this.timeoutObj);
  clearTimeout(_this.serverTimeoutObj);
  _this.startWsHeartbeat()
  }
 };

//抛出 websocket 对象
export default wsConnection

websocket 方法调用

//在 main.js 引入
import wsConnection from './vuex/wsStore'
//挂载 vue 原型链
Vue.prototype.$setWs = wsConnection;

//在使用地方调用
$this.$setWs.initWebSocket();

//在需要使用服务端推送过来的消息时
//在 computed 方法声明
getWsMsg() {
 //在核心代码接收到的服务端信息存储到 vuex 的属性
return this.$store.state.webSocketMsg
 }
 //在 watch 方法 监听 getWsMsg 
getWsMsg: function (data, val) {
  console.log(data);
 //.......
}

以上就是关于在 vue 项目中封装 websocket 使用方法的全部代码。

「点点赞赏,手留余香」

1

给作者打赏,鼓励TA抓紧创作!

微信微信 支付宝支付宝

还没有人赞赏,快来当第一个赞赏的人吧!

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
码云笔记 » vue项目中websocket封装方法的使用

发表回复