tk挠痒痒网址发布页-秘密武器
历史搜索

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

游客2025-05-16 12:34:01

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

核心代码:

//这里需要引入 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 使用方法的全部代码。

标签:vue

本文是由用户"游客"发布,所有内容的版权归原作者所有。没有经过书面许可,任何单位或个人不得以任何形式复制、转载、引用本网站的内容。否则将追究法律责任。

相关专题