• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

vue 项目使用websocket

武飞扬头像
蓝胖子的多啦A梦
帮助1

1. 在utils下新建websocket.js文件

// import { showInfoMsg, showErrorMsg } from '@/utils/popInfo'
import ElementUI from 'element-ui';
function initWebSocket(e) {
    console.log(e)
    const wsUri = WS_API   "/webSocket/"   e;
    this.socket = new WebSocket(wsUri)//这里面的this都指向vue
    this.socket.onerror = webSocketOnError;
    this.socket.onmessage = webSocketOnMessage;
    this.socket.onclose = closeWebsocket;
}
function webSocketOnError(e) {
    ElementUI.Notification({
        title: '',
        message: "WebSocket连接发生错误"   e,
        type: 'error',
        duration: 0,
    });
}
function webSocketOnMessage(e) {
    const data = JSON.parse(e.data);
    console.log(data.msgType === "INFO", data.msgType === "INFO")
    if (data.msgType === "INFO") {
        ElementUI.Notification({
            title: '',
            message: data.msg,
            type: 'success',
            duration: 3000,
        });

    } else if (data.msgType === "ERROR") {
        ElementUI.Notification({
            title: '',
            message: data.msg,
            type: 'error',
            duration: 0,
        });
    }
}
// 关闭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
}
学新通

学新通
学新通
如果想刷新重新链接websocket 可以在App.vue页面里添加个钩子函数

  mounted() {
    //当在任一路由页面被刷新时,便是根组件app被从新建立,此时能够进行webSocket重连
    //从localStorage中获取用户信息,是登陆状态则能够进行webSocket重连
    let token = localStorage.getItem("token");
    if (token) {
      // userMessage = JSON.parse(userMessage);
      this.$websocket.initWebSocket(token);
    }
  },

学新通

客户端主动关闭websocket 在关闭的地方触发函数就可以

 logout() {
      // localStorage.clear();
      localStorage.removeItem("token");
      this.$websocket.close();
      this.$store.dispatch("LogOut").then(() => {
        location.reload();
      });
    },

学新通
注:$webSocket 是在main.js中全局注册了websocket.js文件
学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgbfgif
系列文章
更多 icon
同类精品
更多 icon
继续加载