websocket vue使用

data(){
    return{
        websocket: null,    
    }
}
created() {

    localStorage.setItem('root', process.env.API_ROOT);
},
mounted(){

  //页面刚进入时开启长连接
    var socketUrl = localStorage.getItem('root') + "/carweb/im/" +                localStorage.getItem('message');
    socketUrl = socketUrl.replace("https", "wss").replace("http", "ws");
    this.initWebsocket(socketUrl);
},
methods:{
    //初始化websocket
    async initWebsocket(wbUrl) {
      setTimeout(function () {
        this.websocket = new WebSocket(wbUrl);
        // 连接
        this.websocket.onopen = this.websocketOpen;
        // 接收数据
        this.websocket.onmessage = this.websocketMessage;
        // 错误
        this.websocket.onerror = this.websocketError;
        // 关闭
        this.websocket.onclose = this.websocketclose;

      }.bind(this), 0);
    },
    websocketclose(e) { //关闭 
      console.log("connection closed (" + e.code + ")");
    },
    websocketError(e) {
      console.log('报错', e);
    },
    //发送请求
    async websocketOpen() {
      console.log('websocketOK');
    },
    //websocket链接成功
    async websocketMessage(msg) {
      // 接收数据
      if (msg.data != '') {
        if (this.isJSON(msg.data)) {
          var obj = JSON.parse(msg.data);

          if (obj.type == 'notifyEvent' && obj.data.eventMsg != '' && obj.data.event != '20' && obj.data.event != '21' && obj.data.event != '22') {
            if (sessionStorage.getItem('opersid') > 0) {
              if (obj.data.event == '1' || obj.data.event == '2' || obj.data.event == '3') {
                //司机已接单
                sessionStorage.setItem('mindate', '');
                sessionStorage.setItem('seconds', 0);
                sessionStorage.setItem('opersid', 2);
                this.$router.push('/cfront/orders');
              } else if (obj.data.event == '4' || obj.data.event == '5') {
                //开始计费
                sessionStorage.setItem('opersid', 4);
                this.$router.push('/cfront/OnTheRoad');
              } else if (obj.data.event == '6') {
                //完成
                sessionStorage.setItem('opersid', 0);
                this.$router.push('/cfront/unpaid');
              }
            }

          }
        }
      }
    },
    isJSON(str) {
      if (typeof str == 'string') {
        try {
          var obj = JSON.parse(str);
          if (typeof obj == 'object' && obj) {
            return true;
          } else {
            return false;
          }

        } catch (e) {
          // console.log('error:' + str + '!!!' + e);
          return false;
        }
      }
      // console.log('It is not a string!');
    }
},
destroyed() {
    window.removeEventListener('popstate', this.goBack, false);
  },


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值