zoukankan      html  css  js  c++  java
  • vue使用websoket

    参考链接:https://www.cnblogs.com/qisi007/p/10213886.html

    export default {
        name: "realdetail",
        components: {},
        data() {
          return {
            wsuri: null,
            websock: null
          }
          };
        },
        created() {
            this.wsuri = "ws://127.0.0.1:8210";//监听地址
            this.initWebSocket();
        },
        destroyed() {
          this.websock.close() //离开路由之后断开websocket连接
        },
     methods: {initWebSocket() { //初始化weosocket
            this.websock = new WebSocket(this.wsuri);
            this.websock.onmessage = this.websocketonmessage;
            this.websock.onopen = this.websocketonopen;
            this.websock.onerror = this.websocketonerror;
            this.websock.onclose = this.websocketclose;
          },
          websocketonopen() { //连接建立之后执行send方法发送数据
            let message = {
              type: "login",
              data: {"mn":this.deviceInfo.mn}
            };
            console.log(message);
            this.websocketsend(JSON.stringify(message));
          },
          websocketonerror() { //连接建立失败重连
            this.initWebSocket();
          },
          websocketonmessage(e) { //数据接收
            const redata = JSON.parse(e.data);      console.log(redata)
            this.handlerData(redata);
            this.$forceUpdate(); // 强制刷新一下数据
          },
          websocketsend(Data) { //数据发送
            this.websock.send(Data);
          },
          websocketclose(e) { //关闭
            console.log('断开连接', e);
          },
          handlerData(data) {
            if (data.type) {
              switch (data.type) {
                case "realData":
                  this.updateRealData(data.data);
                  this.deviceInfo.onlineStatus=1;
                  break;
                case "online":
                  this.deviceInfo.onlineStatus=1;
                  break;
                case "offline":
                  this.deviceInfo.onlineStatus=0;
                  break;
              }
            }
          },
          //更新实时数据
          updateRealData(data){
            this.realData=this.handleRealData(data);
          }
        }
    

      在线测试websocket:http://coolaf.com/tool/chattest

  • 相关阅读:
    Python实现MapReduce,wordcount实例,MapReduce实现两表的Join
    structure needs cleaning
    Lifecycle of an ASP.NET MVC 5 Application
    ASP.NET Integration with IIS 7
    Execution order of modules in IIS7
    Assembly Binding redirect: How and Why?
    Cannot See Worker Processes Icon in IIS
    What is the main difference between a key, an IV and a nonce?
    核心玩法的三要素
    ruby各种循环输出数组元素
  • 原文地址:https://www.cnblogs.com/webttt/p/15292425.html
Copyright © 2011-2022 走看看