前端 websocket长连接请求数据

前端 websocket长连接,前端实现方法,需后台配合

定义在methods的方法

getSoket(){
          
   
    let that = this;
    let socket;
    if(typeof(WebSocket) == "undefined") {
          
   
        console.log("您的浏览器不支持WebSocket");
    }else{
          
   
        console.log("您的浏览器支持WebSocket");
                //浏览器支持的、请求数据接口
        var url = window._CONFIG[domianURL].replace("https://","wss://").replace("http://","ws://")+"/"+websocketRealtime;
        //console.log(url,我就是url)
        if(socket!=null){
          
   
            socket.close();
            socket=null;
        }
        //建立连接
        that.socket = new WebSocket(url);
        that.socket.onopen = function(msg) {
          
   
            console.log(msg,"websocket已打开");
            //连接成功给后台传数据crew{后台要求}
            that.socket.send(crew);

            };
            //获得消息事件
            that.socket.onmessage = function(msg) {
          
   
              //发现消息进入开始处理前端触发逻辑
              if(msg.data){
          
   
                //拿到消息处理完赋值that是备份的this,放到data中
                that.aircrew = JSON.parse(msg.data);
                console.log(that.aircrew);
              }
            };
            that.socket.onclose = function() {
          
   
              console.log("websocket已关闭");
              that.socket.close();
            };
            that.socket.onerror = function() {
          
   
              console.log("websocket发生了错误");
            }
        }
},
destroyed () {
          
   
  // 离开页面生命周期函数、离开断开websocket
  this.socket.onclose();
},```
经验分享 程序员 微信小程序 职场和发展