vue中WebSocket


created(){
    this.initWebSocket();
},
beforeDestroy() {    ////关闭时断开socket连接
    this.websocketclose();
},
methods:{
    initWebSocket(address) {
      let userId = this.info.id;
      let roomId = this.$route.query.id;
      let nickname = this.info.nickname;
      // WebSocket与普通的请求所用协议有所不同,ws等同于http,wss等同于https
      // 测试  115.28.185.152:8082
      // 正式  47.104.29.50:8081
      this.websock = new WebSocket(url); //这里是websocket服务地址,这里的地址可以前端根据后台地址参数规则拼成,也可以向后端请求
      this.websock.onopen = this.websocketonopen;
      this.websock.onerror = this.websocketonerror;
      this.websock.onmessage = this.websocketonmessage;
      this.websock.onclose = this.websocketclose;
       //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。Ï
      window.onbeforeunload = this.websocketclose;
    },
    websocketonopen() {
      this.playerOptions.autoplay=true;
      console.log("WebSocket连接成功");
    },
    websocketonerror(e) {
      console.log("WebSocket连接发生错误");
    },
    websocketonmessage(e) {
      let data = JSON.parse(e.data);
      if (data.type !== "1") {
        this.msgs.push(data);
      }
    },
    websocketclose(e) {
       this.websock.close()
      console.log("connection closed "); 
    },}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM