其他分享
首页 > 其他分享> > vue中WebSocket

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 "); 
    },}

标签:vue,WebSocket,websocketclose,let,websock,关闭,data
来源: https://www.cnblogs.com/ljh--/p/12498514.html