vues全局使用WebSocket

// import { showInfoMsg, showErrorMsg } from '@/utils/popInfo'
// import ElementUI from 'element-ui';
import { Toast } from 'vant';
function initWebSocket(baseObj) {
    console.log(baseObj)
    // const wsUri = WS_API + "/webSocket/" + e;
    // var wsUri ="ws://192.168.0.200:8005/qrCodePage/ID=1/refreshTime=5";
    var wsUri = "ws://192.168.11.87:8088/level/gauge/1/2"
    this.socket = new WebSocket(wsUri)//这里面的this都指向vue
      // 监听socket连接
     this.socket.onopen =  WebSocketOnopen;
     // 监听socket错误信息
    this.socket.onerror = webSocketOnError;
     // 监听socket消息
    this.socket.onmessage = webSocketOnMessage;
    // 监听socket关闭
    this.socket.onclose = closeWebsocket;
}
// this.$websocket.close();//全局 关闭
// this.$websocket.initWebSocket(xxx); //全局 吊起
// 监听socket连接
function WebSocketOnopen(e) {
    console.log("socket连接成功")
    Toast("socket连接成功" )
}
 // 监听socket错误信息
function webSocketOnError(e) {
    console.log(e)
    Toast("WebSocket连接发生错误" + e)
}
// 监听socket消息
function webSocketOnMessage(e) {
    console.log(e)
    Toast("接收到信息了")
    let messObj=JSON.parse(e.data)
    if(messObj.code==500){
        this.close() 
        Toast("断开了")
    }
    // console.log('错误信息',e)
    // const data = JSON.parse(e.data);
}

// 关闭websiocket
function closeWebsocket() {
    console.log('连接已关闭...')
}
function close() {
    this.socket.close() // 关闭 websocket
    this.socket.onclose = function (e) {
        console.log(e)//监听关闭事件
        console.log('关闭')
    }
}
function webSocketSend(agentData) {
    this.socket.send(agentData);
}
export default {
    initWebSocket, close
}

 

posted @ 2023-05-30 16:30  ThisCall  阅读(225)  评论(0编辑  收藏  举报