美文网首页Vue技术
Websocket前端实现

Websocket前端实现

作者: 小米和豆豆 | 来源:发表于2021-07-27 14:19 被阅读0次
    1. main.js
    //注册一个消息总线
    Vue.prototype.$bus=new Vue();
    
    1. 封装webkect组件
    <template></template>
    <script>
    export default {
      name: "WebSocket",
      data() {
        return {
            websock:null,
            webSockCheckInterval:null,
            websockIsDestroying:false,
            websockErrTimes:0
        };
      },
      created(){
        if (window.WebSocket) {
              this.initWebSocket()
        }else {
            this.$message.warning("该浏览器不支持提醒。<br/>建议使用高版本的浏览器,<br/>如 IE10、火狐 、谷歌  、搜狗等");
        }
      },
      methods: {
        initWebSocket() {
            this.createWebSocket();
    
            //如果服务端断开重连(保持长连接)
            this.webSockCheckInterval = window.setInterval(() => {
                if (!this.websockIsDestroying && this.websock.readyState === 3) {
                    this.websockErrTimes = 0;
                    this.createWebSocket();
                }
            }, 60000);
        },
        //创建WebSocket(初始化创建及断开重连)
        createWebSocket () {
          let sid='DDY'
            this.websock = new WebSocket(`ws://127.0.0.1:8080/webMsg/${sid}`);
            this.websock.onmessage = this.webSocketOnMessage;
            this.websock.onopen = this.webSocketOnOpen;
            this.websock.onerror = this.webSocketOnError;
            this.websock.onclose = this.websocketOnCose;
        },
        heartBeatReset () {
          this.heartBeatEnd();
          this.heartBeatStart();
        },
        heartBeatEnd () {
          clearTimeout(this.heartTimeOut);
        },
        heartBeatStart () {
          this.heartTimeOut = window.setTimeout(() => {
            var message = {
                operType:'HEART_BEAT',
                message:'test'
            };
            this.webSocketSend(JSON.stringify(message));
          }, 30000);
        },
        //释放WebSocket
        destroyWebSocket () {
          this.websockIsDestroying = true
          if (!!this.websock && this.websock.readyState == 1) {
            this.websock.close();
          }
          window.clearInterval(this.webSockCheckInterval);
          this.heartBeatEnd();
        },
        //创建连接完成事件处理函数
        webSocketOnOpen () {
          this.websockErrTimes = 0;
          this.heartBeatReset();
        },
        //WebSocket异常事件处理函数
        webSocketOnError () {
          window.setTimeout(() => {
            if (++this.websockErrTimes < 5 && !this.websockIsDestroying && this.websock.readyState === 3) {
              //失败重连
              this.createWebSocket()
            }
          }, 3000);
        },
        //消息数据接收事件
        webSocketOnMessage (e) {
          this.heartBeatReset();
          let msgList = JSON.parse(e.data);
          console.log(msgList);
          try {
            let fns = [];
            for (let i = 0, len = msgList.length, msg = null; i < len; i++) {
              msg = msgList[i];
              if (msg.operType != 'HEART_BEAT') fns.push(this.$bus.$emit(msg.operType, msg));
            }
            Promise.all(fns).then(() => {}).catch(() => { })
          }
          catch{ }
        },
        //关闭事件处理程序
        websocketOnCose (e) {  //关闭
          // console.log('close websocket', e);
        },
        //数据发送
        webSocketSend (Data) {
          this.websock.send(Data);
        }
        
      },
      destroyed(){
        console.log('退出')
        this.destroyWebSocket();
      }
    };
    </script>
    
    1. 使用WebSocket组件
    <template>
        <div><WebSocket/></div>
    </template>
    mounted(){
             //重点*******注意
            this.$bus.$off('myEvent')
            //监听消息模块分发的事件
            this.$bus.$on('myEvent',(msg)=>{
                console.log(msg)
            })
        },
      destroyed(){
        console.log('退出')
        //重点*******注意
        this.$bus.$off('myEvent')
      }
    

    相关文章

      网友评论

        本文标题:Websocket前端实现

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