美文网首页
websocket在vue中使用

websocket在vue中使用

作者: 秋玄语道 | 来源:发表于2021-09-13 18:45 被阅读0次

    语音播放会有一个问题,因为浏览器做了限制,只有用户点击了当前页面,才能触发媒体播放。

    <template>
      <div></div>
    </template>
    
    <script>
    export default {
      data() {
        return {
          audio: null,
          socket: null,
          timeout: 30 * 1000,
          heartBeatTimer: null,
          reconnectTimer: null
        }
      },
      methods: {
        initWebSocket() {
          this.createWebSocket();
          this.reconnectTimer = window.setInterval(() => {
            if (this.socket.readyState === 3) {
              this.stopHeartBeat();
              this.createWebSocket();
            }
          }, 60000)
        },
        stopHeartBeat() {
          this.heartBeatTimer = setInterval(() => {
            this.socket.send('hello server!');
          }, this.timeout);
        },
        startHeartBeat() {
          clearInterval(this.heartBeatTimer);
          this.heartBeatTimer = null;
        },
        createWebSocket() {
          const host = window.location.host;
          this.socket = new WebSocket(`wss://${host}/websocket`);
          this.socket.onopen = this.onopen;
          this.socket.onmessage = this.onmessage;
          this.socket.onclose = this.onclose;
          this.socket.onerror = this.onerror;
        },
        //用于指定连接成功后的回调函数。
        onopen(event) {
          this.startHeartBeat();
        },
        //用于指定当从服务器接受到信息时的回调函数。
        onmessage(event) {
          let self = this;
          let message = JSON.parse(event.data);
          if (message.type == 'sessionId') {
            //save sessionId
          } else {
            self.audio.play();
            //做业务处理
          }
        },
        //用于指定连接关闭后的回调函数。
        onclose(event) {
          console.log('成功关闭链接', event);
        },
        //用于指定连接失败后的回调函数。
        onerror(event) {
          console.log('链接出错', event);
        }
      },
      created() {
        this.audio = new Audio(require('./assets/audio/audio.mp3'));
      },
      mounted() {
        this.initWebSocket();
      },
      beforeDestroy() {
        this.socket.close();
        clearInterval(this.heartBeatTimer);
        clearInterval(this.reconnectTimer);
        this.heartBeatTimer = null;
        this.reconnectTimer = null;
      }
    }
    </script>
    
    

    相关文章

      网友评论

          本文标题:websocket在vue中使用

          本文链接:https://www.haomeiwen.com/subject/whbfgltx.html