zoukankan      html  css  js  c++  java
  • 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>
  • 相关阅读:
    JSP中的一个树型结构
    访问SAP的RFC
    MySQL InnoDB的一些参数说明
    Python: 去掉字符串中的非数字(或非字母)字符
    获取百度地图代码方法
    ps修图之——四步去修图后的毛边
    Python中给文件加锁
    问答项目---金币经验奖励规则及网站配置写入config文件
    问答项目---封装打印数组的方法
    问答项目---栏目增删改方法示例
  • 原文地址:https://www.cnblogs.com/jinsuo/p/13617189.html
Copyright © 2011-2022 走看看