# Vue前端WebSocket接入文档 ## 📋 环境要求 - Vue 2.x / Vue 3.x - SockJS客户端 - STOMP.js客户端 ## 🔧 安装依赖 ```bash npm install sockjs-client @stomp/stompjs ``` ## 📝 接入步骤 ### 1. 引入WebSocket库 ```javascript import SockJS from 'sockjs-client'; import { Client } from '@stomp/stompjs'; ``` ### 2. 创建WebSocket服务 ```javascript // websocket.service.js export class WebSocketService { constructor() { this.client = null; this.connected = false; this.reconnectAttempts = 0; this.maxReconnectAttempts = 5; } connect(token) { if (this.connected) return Promise.resolve(); return new Promise((resolve, reject) => { // 建立WebSocket连接 const socket = new SockJS('http://localhost:8080/ws-notification'); this.client = new Client({ webSocketFactory: () => socket, connectHeaders: { Authorization: token }, debug: (str) => console.log('STOMP Debug:', str), reconnectDelay: 5000, heartbeatIncoming: 4000, heartbeatOutgoing: 4000, }); // 连接成功回调 this.client.onConnect = (frame) => { console.log('WebSocket连接成功:', frame); this.connected = true; this.reconnectAttempts = 0; this.subscribeToChannels(); resolve(frame); }; // 连接失败回调 this.client.onStompError = (frame) => { console.error('WebSocket连接失败:', frame); this.connected = false; reject(frame); }; // 断开连接回调 this.client.onDisconnect = () => { console.log('WebSocket连接断开'); this.connected = false; this.handleReconnect(); }; // 启动连接 this.client.activate(); }); } // 订阅消息频道 subscribeToChannels() { if (!this.connected) return; // 订阅个人消息 this.client.subscribe('/user/queue/notifications', (message) => { const notification = JSON.parse(message.body); this.handleMessage(notification); }); // 订阅系统消息 this.client.subscribe('/user/queue/system', (message) => { const notification = JSON.parse(message.body); this.handleMessage(notification); }); // 订阅广播消息 this.client.subscribe('/topic/broadcast', (message) => { const notification = JSON.parse(message.body); this.handleMessage(notification); }); } // 处理接收到的消息 handleMessage(notification) { console.log('收到消息:', notification); // 触发全局事件 window.dispatchEvent(new CustomEvent('websocket-message', { detail: notification })); // 根据消息类型处理 switch (notification.messageType) { case 'SYSTEM': this.handleSystemMessage(notification); break; case 'EMERGENCY': this.handleEmergencyMessage(notification); break; default: this.handleDefaultMessage(notification); } } // 发送消息 sendMessage(destination, body) { if (!this.connected) { console.error('WebSocket未连接'); return Promise.reject('WebSocket未连接'); } return new Promise((resolve, reject) => { this.client.publish({ destination: destination, body: JSON.stringify(body) }); resolve(); }); } // 断开连接 disconnect() { if (this.client) { this.client.deactivate(); this.connected = false; } } // 自动重连 handleReconnect() { if (this.reconnectAttempts < this.maxReconnectAttempts) { this.reconnectAttempts++; console.log(`尝试重连 (${this.reconnectAttempts}/${this.maxReconnectAttempts})`); setTimeout(() => { this.connect(); }, 5000); } else { console.error('重连次数已达上限'); } } } ``` ### 3. 在Vue组件中使用 ```vue 状态: {{ statusText }} 未读消息: {{ unreadCount }} {{ message.title }} {{ message.messageType }} {{ message.content }} {{ formatTime(message.sendTime) }} 连接WebSocket 断开连接 发送测试消息 ``` ## 🚀 使用说明 1. **安装依赖**: `npm install sockjs-client @stomp/stompjs` 2. **创建服务**: 复制 `WebSocketService` 类到项目中 3. **集成组件**: 在需要的Vue组件中使用 4. **处理消息**: 监听 `websocket-message` 事件 5. **错误处理**: 实现重连机制和错误提示 ## ⚠️ 注意事项 - 确保Token有效且格式正确 - 处理网络断开和重连 - 及时清理事件监听器 - 适配后端API接口格式