Vue通过WebSocket建立长连接的实现代码

Vue通过WebSocket建立长连接的实现代码

使用场景:

在项目开发中,后端需要处理一连串的逻辑,或者等待第三方的数据返回来进行处理之后在返回给前端,可能时间会很长,而且前端也不知道后端什么时候能处理好(时间长的话会达到10分钟左右),如果采用普通的HTTP连接,前后端无法一直保持联系,麻烦的时候可能还需要采用轮询的机制,所以使用WebSocket连接效果还是比较好的。

使用时间:

在界面加载完之后,建上WebSocket连接,此时前端还可以发送普通的HTTP的请求,等到后端处理完之后,通过建立的WebSocket连接返给前端,前端根据返回的数据进行对应的操作。

代码展示:

<template>
</template>
<script>
export default {
 data() {
  return{
   // 用户Id
   userId:'',
   appid:'',
   // 事件类型
   type:'',
   msg:'',
   wsUrl:''
  }  
 },
 methods: {
  //初始化weosocket
  initWebSocket() {
   if (typeof WebSocket === "undefined") {
    alert("您的浏览器不支持WebSocket");
    return false;
   }
   const wsuri = 'ws://(后端WebSocket地址)/websocket/' + this.userId + '/' + this.appid // websocket地址
   this.websock = new WebSocket(wsuri);
   this.websock.onopen = this.websocketonopen;
   this.websock.onmessage = this.websocketonmessage;
   this.websock.onerror = this.websocketonerror;
   this.websock.onclose = this.websocketclose;
  },
  //连接成功
  websocketonopen() {
   console.log("WebSocket连接成功");
   // 添加心跳检测,每30秒发一次数据,防止连接断开(这跟服务器的设置有关,如果服务器没有设置每隔多长时间不发消息断开,可以不进行心跳设置)
   let self = this;
   this.timer = setInterval(() => {
    try {
     self.websock.send('test')
     console.log('发送消息');
    }catch(err){
     console.log('断开了:' + err);
     self.connection()
    }
   }, 30000)
  },
  //接收后端返回的数据,可以根据需要进行处理
  websocketonmessage(e) {
   var vm = this;
   let data1Json = JSON.parse(e.data);
   console.log(data1Json);
  },
  //连接建立失败重连
  websocketonerror(e) {
   console.log(`连接失败的信息:`, e);
   this.initWebSocket(); // 连接失败后尝试重新连接
  },
  //关闭连接
  websocketclose(e) {
   console.log("断开连接", e);
  }
 },
 created() {
  if (this.websock) {
   this.websock.close(); // 关闭websocket连接
  }
  this.initWebSocket();
 },
 destroyed() {
  //页面销毁时关闭ws连接
  if (this.websock) {
   this.websock.close(); // 关闭websocket
  }
 }
};
</script>

问题回顾:

在实际使用的时候遇到的问题:有的时候页面链接还没有建立上,但是后端已经把数据都处理好了,这个时候推给前端,前端接收不到。

解决方案:

1)简单的方法:让后端延迟几秒再推

优势:简单

劣势:降低了性能

2)优化之后的方法:使用Redis保存用户的登录状态,缓存这个用户的数据,等到建立连接之后再推,推完就清空Redis

当然,我们还有更方便快捷的在vue中使用websocket的方法,那就是使用GoEasy提供的websocket服务。

目前GoEasy提供完整的websocket前后端解决方案,简单的几行代码集成,即可快速搭建您的专属websocket服务。 同时支持各种前端技术框架如小程序、uniapp、vue,支持各种服务端语言如php、java、python等。对websocket有需求的开发者可以来注册试用一下【立即注册

Comments are closed.