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); }); }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 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插件