使用websocket实现实时推送

1.Websocket概述

      websocket是客户端和服务器端进行交互的简单协议,在websocket中,服务器和浏览器只需要进行一次握手,两者之间就可以建立持久的连接性,并可以进行双向的数据传送。

2.Websocket的使用

 // 初始化websocket
      initWebsocket() {
        this.userInfo = Tools.getLoc('userInfo');
        this.userId = this.userInfo.id;
        const wsuri = "ws://地址;
        this.websocket = new WebSocket(wsuri);
        this.websocket.onmessage = this.websocketonmessage;
        this.websocket.onopen = this.websocketopen;
        this.websocket.onerror = this.websocketonerror;
        this.websocket.onclose = this.websocketclose;
      },
      // 接收数据
      websocketonmessage(e) {
        console.log(typeof e.data);  //为string类型
        this.data = e.data;      //接收到的数据
        let H = new Date().getHours(); //获取小时
        let M = new Date().getMinutes();// 获取分钟
        this.time = H + ":" + M;
        let timeAndData = {
          time: this.time,
          data: this.data
        };
        this.Datas.unshift(timeAndData); 
      },
      // 建立连接
      websocketopen() {
        // console.log("建立了连接");
      },
      // 连接失败
      websocketonerror() {
        this.initWebsocket();
        // console.log("连接失败,重新连接");
      },
      // 断开连接
      websocketclose(event) {
        // console.log("断开连接",event);
      },
      // 发送数据
      websocketsend(Data) {
        this.websocket.send(Data);
      },

3.将获取的时间和事件绑定到页面

          <ul>
              <li v-for="Data in Datas">
                <div>
                  <span class="timeline-tag">{{Data.time}}</span>
                  <span class="timeline-text">{{Data.data}}</span>
                </div>
              </li>
            </ul>

猜你喜欢

转载自blog.csdn.net/qq_41550865/article/details/87687740