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

  • 相关阅读:
    Docker构建Centos7容器
    Docker命令大全
    win10常用开发配置
    git小结
    JSP页面The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path错误处理
    CentOS 设置mysql的远程访问
    CentOS安装MySQL
    Kali对wifi的破解记录
    MyEclipse对Maven的安装
    关于sqlmap的使用
  • 原文地址:https://www.cnblogs.com/webttt/p/15292425.html
Copyright © 2011-2022 走看看