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

AI 概述
这套代码目前个人在项目中已使用,大家可以直接拿去使用,相关注意点已在代码中注释,方便大家阅读。 核心代码: //这里需要引入 vuex import store from './store'; let wsConnection = { $ws: null, lockReturn: false, timeout: 60 * 1000 * 5, timeoutObj: null, timeoutNum: null, serverTimeoutOb...

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

核心代码:

//这里需要引入 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项目中websocket封装方法的使用的文章就介绍到这了,更多相关内容请搜索码云笔记以前的文章或继续浏览下面的相关文章,希望大家以后多多支持码云笔记。

「点点赞赏,手留余香」

1

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

微信微信 支付宝支付宝

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

声明:本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若内容造成侵权/违法违规/事实不符,请将相关资料发送至 admin@mybj123.com 进行投诉反馈,一经查实,立即处理!
重要:如软件存在付费、会员、充值等,均属软件开发者或所属公司行为,与本站无关,网友需自行判断
码云笔记 » vue项目中websocket封装方法的使用

发表回复