vue项目调用WebSocket

<template>
<div></div>
<!--  <el-button @click="sendDataToServer" >给后台发送消息</el-button>-->
</template>

<script>
  import { listToRead } from "@/api/invest/message";
  export default {
    name: "WebSocket",
    data() {
      return {
        // ws是否启动
        wsIsRun: false,
        // 定义ws对象
        webSocket: null,
        // ws请求链接(类似于ws后台地址)
        ws: '',
        // ws定时器
        wsTimer: null,
      }
    },
    async mounted() {
      this.wsIsRun = true
      this.wsInit()
    },
    methods: {
      listToRead(){
        listToRead().then(res=>{
          this.$emit('messageNum',res.data)
        })
      },
      sendDataToServer() {
        if (this.webSocket.readyState === 1) {
          this.webSocket.send('来自前端的数据')
        } else {
          throw Error('服务未连接')
        }
      },
      /**
       * 初始化ws
       */
      wsInit() {
        let host = window.location.host;
        let userId = JSON.parse(sessionStorage.getItem('user')).userId
        let url = process.env.VUE_APP_BASE_API
        // const wsuri = 'ws://10.81.36.173:8080/websocket/1'
        const wsuri = 'ws://'+`${host}`+`${url}` + '/websocket/' +`${userId}`
        // const wsuri = 'ws://localhost/dev-api/websocket/1'
        console.log(wsuri);
        this.ws = wsuri
        if (!this.wsIsRun) return
        // 销毁ws
        this.wsDestroy()
        // 初始化ws
        this.webSocket = new WebSocket(this.ws)
        // ws连接建立时触发
        this.webSocket.addEventListener('open', this.wsOpenHanler)
        // ws服务端给客户端推送消息
        this.webSocket.addEventListener('message', this.wsMessageHanler)
        // ws通信发生错误时触发
        this.webSocket.addEventListener('error', this.wsErrorHanler)
        // ws关闭时触发
        this.webSocket.addEventListener('close', this.wsCloseHanler)

        // 检查ws连接状态,readyState值为0表示尚未连接,1表示建立连接,2正在关闭连接,3已经关闭或无法打开
        clearInterval(this.wsTimer)
        this.wsTimer = setInterval(() => {
          if (this.webSocket.readyState === 1) {
            clearInterval(this.wsTimer)
          } else {
            console.log('ws建立连接失败')
            this.wsInit()
          }
        }, 3000)
      },
      wsOpenHanler(event) {
        //初始化消息通知
        this.listToRead();
        console.log('ws建立连接成功')
      },
      wsMessageHanler(e) {
        //当有新的消息通知时
        this.listToRead();
        //websocket 弹出框展示的数据库
        let redata
        try{
          redata = JSON.parse(e.data);
        }catch (e) {
          return;
        }
        if(redata) {
          var that = this;
          this.$notify.info({
            title: redata.memo,
            message: redata.content,
            position: "bottom-right",
            duration: 0,
            data:redata,
            onClick() {
              let row = this.data;
              if(row.source=="1"){
                row.mid=row.addr
                that.$router.push({
                  name:"Meetinglook",
                  query:row
                })
                return read({sourceId:row.sourceId})
              }
              if(row.source=="2"){
                row.mid=row.addr
                that.$router.push({
                  name:"Meetinglook",
                  query:row
                })
                return read({sourceId:row.sourceId})
              }
              if(row.source=="3"){
                row.mid=row.addr
                that.$router.push({
                  name:"Meetinglook",
                  query:row
                })
                return read({sourceId:row.sourceId})
              }
              if(row.source=="4"){
                row.tid=row.addr
                that.$router.push({
                  name:"Topic",
                  query:row
                })
                return read({sourceId:row.sourceId})
              }
              if(row.source=="5"){
                row.tid=row.addr
                that.$router.push({
                  name:"Topic",
                  query:row
                })
                return read({sourceId:row.sourceId})
              }
              if(row.source=="21"){
                row.pid=row.addr
                that.$router.push({
                  name:"Survey",
                  query:row
                })
                return read({sourceId:row.sourceId})
              }
              if(row.source=="22"){
                row.pid=row.addr
                that.$router.push({
                  name:"Survey",
                  query:row
                })
                return read({sourceId:row.sourceId})
              }
              if(row.source=="31"){
                row.pid=row.addr
                that.$router.push({
                  name:"Surveys",
                  query:row
                })
                return read({sourceId:row.sourceId})
              }
              if(row.source=="32"){
                row.pid=row.addr
                that.$router.push({
                  name:"Surveys",
                  query:row
                })
                return read({sourceId:row.sourceId})
              }
              if(row.source=="41"){
                row.did=row.addr
                that.$router.push({
                  name:"DynamicSee",
                  query:row
                })
                return read({sourceId:row.sourceId})
              }
              if(row.source=="42"){
                row.did=row.addr
                that.$router.push({
                  name:"DynamicSee",
                  query:row
                })
                return read({sourceId:row.sourceId})
              }
            }
          });
        }

      },
      /**
       * ws通信发生错误
       */
      wsErrorHanler(event) {
        console.log(event, '通信发生错误')
        this.wsInit()
      },
      /**
       * ws关闭
       */
      wsCloseHanler(event) {
        console.log(event, 'ws关闭')
        this.wsInit()
      },
      /**
       * 销毁ws
       */
      wsDestroy() {
        if (this.webSocket !== null) {
          this.webSocket.removeEventListener('open', this.wsOpenHanler)
          this.webSocket.removeEventListener('message', this.wsMessageHanler)
          this.webSocket.removeEventListener('error', this.wsErrorHanler)
          this.webSocket.removeEventListener('close', this.wsCloseHanler)
          this.webSocket.close()
          this.webSocket = null
          clearInterval(this.wsTimer)
        }
      },
    }
  }
</script>

<style>
 .el-notification__group   {
   word-break: break-all;
 }
</style>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值