随笔 - 261  文章 - 0  评论 - 22  阅读 - 55万

vue中使用sockjs

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);
      });
    }

 

 

 

 

 
posted on   紅葉  阅读(1152)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
历史上的今天:
2019-08-14 redux简单使用
2019-08-14 vsCode插件
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示