温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在Vue中使用WebSocket建立长连接

发布时间:2021-04-17 17:12:16 来源:亿速云 阅读:1193 作者:Leah 栏目:web开发

怎么在Vue中使用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建立长连接的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI