webSocket在vue中应用

本文介绍了一个使用Vue.js实现的WebSocket连接示例,包括连接初始化、错误处理、接收消息及心跳保持等功能。通过具体代码展示了如何与服务器进行双向通信,并处理接收到的消息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  methods: {
      initWebSocket() {
        var userId=this.$store.getters.user.id
        const wsUri = process.env.VUE_APP_WS_API + '/webSocket?uid=' + userId
        this.websock = new WebSocket(wsUri)
        this.websock.onerror = this.webSocketOnError
        this.websock.onmessage = this.webSocketOnMessage
        this.websock.onclose = this.closeWebSocket
        this.websock.onopen = this.onopen
      },
      webSocketOnError(e) {
        this.$notify({
          title: 'WebSocket连接发生错误',
          type: 'error',
          duration: 0
        })
      },
      //关闭WebSocket连接
      closeWebSocket(e) {
        console.log("WebSocket关闭连接1");
        this.websocket.close();
        console.log("WebSocket关闭连接2");
        this.initWebSocket()
      },
        //连接成功建立的回调方法
        onopen() {
          console.log("WebSocket连接成功");
          // 建立连接
          var userId=this.$store.getters.user.id
          const wsUri = process.env.VUE_APP_WS_API + '/webSocket?uid=' + userId
          var message = {
            type: "ping"
          };
          var socket = new WebSocket(wsUri);
            var timer = window.setInterval(function(){ //每隔5秒钟发送一次心跳,避免websocket连接因超时而自动断开
              console.log('每隔5秒钟发送一次心跳'+socket.readyState);
              socket.send(JSON.stringify(message))
            },1000*5);


        },
      webSocketOnMessage(e) {
        var userId=this.$store.getters.user.id
        var _that=this
        const obj = JSON.parse(e.data)
            if(obj.addressee ==userId) {
              _that.$alert(obj.messageContent, obj.newsTitle, {
                confirmButtonText: '确定',
                showClose: false,
                callback: action => {
                  request({
                    url: "api/crNews/updataRead",
                    method: 'post',
                    data: {
                      "id": obj.id,
                      "readState": 1
                    }
                  }).then(res => {
                    var path = _that.$route.path
                    if (path == '/taskmanagement/crtaskapi') {
                      window.location.reload()
                    } else {
                      _that.$router.push({
                        path: '/taskmanagement/crtaskapi',
                      })
                    }

                  });
                }
              });
            }
      },
      // initWebSocket() {
      //   var userId=this.$store.getters.user.id
      //   var _that=this
      //
      //   const wsUri = process.env.VUE_APP_WS_API + '/webSocket?uid=' + userId
      //   this.websocket = new WebSocket(wsUri)
      //   // this.websock.onerror = this.webSocketOnError
      //   // this.websock.onmessage = this.webSocketOnMessage
      //
      //   //连接发生错误的回调方法
      //   this.websocket.onerror = function () {
      //     console.log("WebSocket连接发生错误");
      //   };
      //
      //   //连接成功建立的回调方法
      //   this.websocket.onopen = function () {
      //     console.log("WebSocket连接成功");
      //   }
      //
      //   //接收到消息的回调方法
      //   this.websocket.onmessage = function (event) {
      //     console.log("接收到消息的回调方法"+event.data);
      //     var obj = JSON.parse(event.data);// jsonstr是json字符串
      //     if(obj.addressee ==userId){
      //       _that.$alert(obj.messageContent,obj.newsTitle, {
      //         confirmButtonText: '确定',
      //         showClose:false,
      //         callback: action => {
      //           request({
      //             url: "api/crNews/updataRead",
      //             method: 'post',
      //             data: {
      //               "id": obj.id,
      //               "readState":1
      //             }
      //           }).then(res => {
      //             var path= _that.$route.path
      //             if(path=='/taskmanagement/crtaskapi'){
      //               window.location.reload()
      //             }else {
      //               _that.$router.push({
      //                 path: '/taskmanagement/crtaskapi',
      //               })
      //             }
      //
      //           });
      //         }
      //       });
      //
      //     }
      //   }
      //
      //   //连接关闭的回调方法
      //   this.websocket.onclose = function () {
      //     console.log("WebSocket连接关闭");
      //     this.websocket.close();
      //   }
      //
      //   //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
      //   window.onbeforeunload = function () {
      //     this.websocket.close();
      //   }
      // },


      callbackMethod(dataStr,userId){//消息发送成功回调的方法
        var obj = JSON.parse(dataStr);// jsonstr是json字符串
        if(obj.addressee==userId){
          this.$alert('这是一段内容', '标题名称', {
              confirmButtonText: '确定',
              callback: action => {
                this.$message({
                  type: 'info',
                  message: `action: ${ action }`
                });
              }
            });

        }
      },


      toggleSideBar() {
        this.$store.dispatch('app/toggleSideBar')
      },
      open() {
        this.$confirm('确定注销并退出系统吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.logout()
        })
      },
      logout() {
        this.$store.dispatch('LogOut').then(() => {
          location.reload()
        })
      }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值