# WebSocket 使用示例 ## 📦 已创建的文件 ✅ `/utils/websocket-manager.js` - WebSocket 管理器(已完成) --- ## 🚀 快速开始 ### 1. 在 App.vue 中初始化连接 ```vue ``` --- ### 2. 在聊天页面中使用 #### 方式 A:修改现有的 `dialogBox.vue` ```vue ``` --- ### 3. 在 Vuex 中管理 WebSocket 状态(可选) ```javascript // store/index.js export default new Vuex.Store({ state: { // ... 其他状态 wsConnected: false, unreadCount: 0, messages: [] }, mutations: { // WebSocket 连接状态 SET_WS_CONNECTED(state, connected) { state.wsConnected = connected }, // 新消息 ADD_MESSAGE(state, message) { state.messages.push(message) state.unreadCount++ }, // 清空未读 CLEAR_UNREAD(state) { state.unreadCount = 0 } }, actions: { // 在 App.vue 中调用 wsConnected({ commit }) { commit('SET_WS_CONNECTED', true) }, wsDisconnected({ commit }) { commit('SET_WS_CONNECTED', false) } } }) ``` --- ## 📋 消息协议设计 ### 客户端 → 服务器 #### 1. 发送文字消息 ```json { "type": "message", "fromUserId": "user123", "toUserId": "user456", "content": "你好", "timestamp": 1635678901234 } ``` #### 2. 发送心跳 ```json { "type": "ping", "timestamp": 1635678901234 } ``` #### 3. 发送已读回执 ```json { "type": "read", "messageId": "msg123", "userId": "user123" } ``` --- ### 服务器 → 客户端 #### 1. 推送消息 ```json { "type": "message", "messageId": "msg123", "fromUserId": "user456", "toUserId": "user123", "content": "你好", "timestamp": 1635678901234 } ``` #### 2. 心跳响应 ```json { "type": "pong", "timestamp": 1635678901234 } ``` #### 3. 系统通知 ```json { "type": "notification", "content": "系统维护通知", "timestamp": 1635678901234 } ``` #### 4. 错误消息 ```json { "type": "error", "code": 401, "message": "未授权", "timestamp": 1635678901234 } ``` --- ## 🔧 后端实现参考 ### Node.js + ws ```javascript const WebSocket = require('ws') const wss = new WebSocket.Server({ port: 8080 }) // 存储所有连接(用户 ID -> WebSocket) const clients = new Map() wss.on('connection', (ws, req) => { // 从 URL 获取 token const token = new URL(req.url, 'http://localhost').searchParams.get('token') // 验证 token,获取用户 ID const userId = verifyToken(token) if (!userId) { ws.close(4001, '未授权') return } // 保存连接 clients.set(userId, ws) console.log(`用户 ${userId} 已连接`) // 处理消息 ws.on('message', (message) => { const data = JSON.parse(message) switch (data.type) { case 'message': // 转发消息 handleMessage(data) break case 'ping': // 心跳响应 ws.send(JSON.stringify({ type: 'pong', timestamp: Date.now() })) break case 'read': // 已读回执 handleReadReceipt(data) break } }) // 处理断开 ws.on('close', () => { clients.delete(userId) console.log(`用户 ${userId} 已断开`) }) }) // 转发消息 function handleMessage(data) { const { toUserId, fromUserId, content } = data // 保存到数据库 saveMessage({ fromUserId, toUserId, content }) // 推送给接收者 const targetWs = clients.get(toUserId) if (targetWs && targetWs.readyState === WebSocket.OPEN) { targetWs.send(JSON.stringify({ type: 'message', messageId: generateId(), fromUserId, toUserId, content, timestamp: Date.now() })) } } ``` --- ## 📊 完整流程图 ``` ┌─────────────┐ │ App 启动 │ └──────┬──────┘ │ ▼ ┌─────────────┐ │ 检查登录状态 │ └──────┬──────┘ │ ▼ (已登录) ┌─────────────┐ │ 连接 WS │ ← wsManager.connect() └──────┬──────┘ │ ▼ ┌─────────────┐ │ 监听消息 │ ← wsManager.on('message') └──────┬──────┘ │ ├─→ (收到消息) → 更新 UI │ └─→ (发送消息) → wsManager.send() │ ▼ ┌─────────────┐ │ 服务器处理 │ └──────┬──────┘ │ ▼ ┌─────────────┐ │ 推送给对方 │ └─────────────┘ ``` --- ## ✅ 测试清单 ### 功能测试 - [ ] 连接成功 - [ ] 发送消息 - [ ] 接收消息 - [ ] 心跳正常 - [ ] 手动断开 - [ ] 自动重连 - [ ] 消息队列 ### 场景测试 - [ ] App 切换到后台 - [ ] App 从后台恢复 - [ ] 网络断开 - [ ] 网络恢复 - [ ] 服务器重启 - [ ] 并发多人聊天 ### 性能测试 - [ ] 消息延迟 < 200ms - [ ] 重连时间 < 5s - [ ] 内存占用正常 - [ ] CPU 占用正常 --- ## 🎉 总结 现在你已经有: 1. ✅ **WebSocket 管理器** (`utils/websocket-manager.js`) - 自动重连 - 心跳检测 - 消息队列 - 事件监听 2. ✅ **使用示例** - App.vue 初始化 - 聊天页面使用 - Vuex 状态管理 3. ✅ **消息协议** - 客户端 → 服务器 - 服务器 → 客户端 4. ✅ **后端参考** - Node.js + ws 实现 --- ## 🚀 下一步 1. **确认后端技术栈** - 告诉我你用什么后端,我帮你写完整的服务端代码 2. **集成到现有聊天页面** - 我帮你修改 `dialogBox.vue` 3. **添加更多功能** - 图片消息 - 语音消息 - 消息已读 - 输入中状态 随时告诉我需要什么!🎯