前端websocket建立以及通信

// 页面建立socket
    socket(){
      var that = this;
      let token = localStorage.getItem("Admin-Token");
      let username = localStorage.getItem("user");
      let id = that.deviceId;
      that.websocket = new window.WebSocket(`${process.env.VUE_APP_websocketUrl}/websocket/${username}/${id}`,[token]);
      //连接关闭的回调方法  
      that.websocket.onclose = that.websocketonclose;
      // 连接错误
      that.websocket.onerror = that.websocketonerror;
      //连接成功时的回调方法  
      that.websocket.onopen = that.websocketonopen;
      //接收到消息的回调方法  
      that.websocket.onmessage = that.websocketonmessage;
    },
    // socket关闭
    websocketonclose(){
       console.log('连接关闭!')
    },
    // socket连接错误
    websocketonerror(){
       console.log('连接错误!');
       var that = this;
       that.socket();
    },
    // 连接成功时的回调方法
    websocketonopen(){
      console.log('连接成功!')
      var that = this;
      let actions = {"id":that.deviceId};
      that.websocketsend(JSON.stringify(actions));
    },
    //接收到消息的回调方法 
    websocketonmessage(msg){
       console.log(msg.data, 'ws:data')
    },
    //数据发送
    websocketsend(Data){
        this.websock.send(Data);
    },

  

上一篇:websokets服务器发消息给客户端


下一篇:SpringBoot+WebSocket 实现简易聊天室