vue中使用sockjs

发布时间 2023-08-14 17:33:34作者: 紅葉

1,安装依赖

npm install sockjs-client --save
npm install stompjs --save

2,使用混入封装

在src下创建mixins文件夹,然后创建sockjs.js文件
import SockJS from "sockjs-client";
import Stomp from "stompjs";
export const sockjsMixins = {
  data() {
    return {
      timer: null,
      subscription: null,
    };
  },
  activated() {
    this.createStompClient();
  },
  deactivated() {
    this.disconnect();
    clearInterval(this.timer);
  },
  beforeDestroy: function () {
    // 页面离开时断开连接,清除定时器
    this.disconnect();
    clearInterval(this.timer);
  },
  methods: {
    createStompClient() {
      const self = this;
      // 建立连接对象
      this.socket = new SockJS("http://xxxxxx:8089/ws", null, {
        timeout: 15000,
      }); //连接服务端提供的通信接口,连接以后才可以订阅广播消息和个人消息
      // 获取STOMP子协议的客户端对象
      this.stompClient = Stomp.over(this.socket);
      // 定义客户端的认证信息,按需求配置
      var headers = {
        login: "mylogin",
        "client-id": "my-client-id",
      };
      // 向服务器发起websocket连接
      this.stompClient.connect(
        headers,
        () => {
          //连接成功,发送订阅
          self.clientOnConnectHandle();
        },
        (err) => {
          // 连接发生错误时的处理函数
          console.log(err);
        },
        (val) => {
          // 订阅连接断开事件
          self.clientOnDisconnectHandle();
        }
      );
    },
    // 断开连接
    disconnect() {
      if (this.stompClient != null) {
        this.stompClient.disconnect();
        this.unsubscribe();
        this.stompClient = null;
      }
    },

    // 订阅连接断开事件
    clientOnDisconnectHandle() {
      const that = this;
      that.closeStompClient(); // 先关闭之前的socket连接
      this.timer = window.setTimeout(() => {
        that.createStompClient(); // 再重新创建一个新的socket连接
        window.clearTimeout(that.reload);
      }, 2000);
    },

    // 清除订阅
    unsubscribe() {
      if (this.subscription) {
        this.subscription.unsubscribe();
        this.subscription = null;
      }
    },

    // 关闭之前的socket连接
    closeStompClient() {
      if (this.stompClient) {
        this.unsubscribe();
        this.stompClient = null; // 清空stompClient对象
      }
    },
  },
};

使用sockjs

在需要调用的页面引入sockjs

import { sockjsMixins } from '@/mixins/sockjs.js
  mixins: [sockjsMixins],

在methods中使用

 clientOnConnectHandle() {
      this.subscription = this.stompClient.subscribe("/topic/chat_msg", (msg) => {
        consolel.log(msg.body);
      });
    }