Vue实现WebSocket实时通信全攻略

张开发
2026/4/8 14:56:23 15 分钟阅读

分享文章

Vue实现WebSocket实时通信全攻略
在Vue中实现WebSocket实时通信可通过以下步骤完成1. 基础实现在Vue组件中创建WebSocket连接并处理实时事件script export default { data() { return { ws: null, messages: [], inputMsg: } }, mounted() { // 建立WebSocket连接 this.ws new WebSocket(wss://your-server-endpoint) // 连接成功回调 this.ws.onopen () { console.log(WebSocket连接已建立) } // 接收消息处理 this.ws.onmessage (event) { this.messages.push(JSON.parse(event.data)) } // 错误处理 this.ws.onerror (error) { console.error(WebSocket错误:, error) } // 关闭连接处理 this.ws.onclose () { console.log(WebSocket连接已关闭) } }, methods: { sendMessage() { if (this.inputMsg.trim() this.ws.readyState WebSocket.OPEN) { const message { content: this.inputMsg, timestamp: new Date().toISOString() } this.ws.send(JSON.stringify(message)) this.inputMsg } } }, beforeUnmount() { // 组件销毁前关闭连接 if (this.ws) { this.ws.close() } } } /script2. 关键优化点连接状态管理添加连接状态指示器template div :class[status, connectionStatus] {{ statusText }} /div /template script // 在data中添加 connectionStatus: disconnected, // disconnected/connecting/connected // 在websocket事件中更新状态 this.ws.onopen () { this.connectionStatus connected } this.ws.onclose () { this.connectionStatus disconnected } /script自动重连机制reconnect(){if(this.reconnectAttempts5)returnsetTimeout((){console.log(尝试重连 (${this.reconnectAttempts}))this.initWebSocket()this.reconnectAttempts},3000*this.reconnectAttempts)}心跳检测startHeartbeat(){this.heartbeatIntervalsetInterval((){if(this.ws.readyStateWebSocket.OPEN){this.ws.send(JSON.stringify({type:heartbeat}))}},30000)}3. 完整组件示例template div classchat-container div classstatus-indicator :classconnectionStatus/div div classmessage-list div v-for(msg, index) in messages :keyindex {{ msg.timestamp }}: {{ msg.content }} /div /div input v-modelinputMsg keyup.entersendMessage button clicksendMessage发送/button /div /template script export default { data() { return { ws: null, messages: [], inputMsg: , connectionStatus: disconnected, reconnectAttempts: 0, heartbeatInterval: null } }, computed: { statusText() { return { disconnected: 连接断开, connecting: 连接中..., connected: 已连接 }[this.connectionStatus] } }, methods: { initWebSocket() { this.connectionStatus connecting this.ws new WebSocket(wss://your-api.example/ws) this.ws.onopen () { this.connectionStatus connected this.reconnectAttempts 0 this.startHeartbeat() } this.ws.onmessage (event) { const data JSON.parse(event.data) if (data.type ! heartbeat) { this.messages.push(data) } } this.ws.onclose () { clearInterval(this.heartbeatInterval) this.connectionStatus disconnected this.reconnect() } }, sendMessage() { // 发送实现... }, reconnect() { // 重连实现... }, startHeartbeat() { // 心跳实现... } }, mounted() { this.initWebSocket() }, beforeUnmount() { this.ws?.close() clearInterval(this.heartbeatInterval) } } /script4. 服务端注意事项消息协议建议使用JSON格式包含消息类型字段{type:message|notification|heartbeat,data:{...}}连接管理服务端需维护连接池管理客户端连接广播机制实现消息广播功能如// Node.js示例clients.forEach(client{if(client.readyStateWebSocket.OPEN){client.send(JSON.stringify(broadcastMsg))}})5. 安全实践使用wss://协议加密通信添加JWT认证mounted(){consttokenlocalStorage.getItem(jwt)this.wsnewWebSocket(wss://api.example/ws?token${token})}消息内容过滤防止XSS攻击限制消息大小服务端/客户端双端验证实际部署时需根据业务需求调整消息协议、重连策略和错误处理机制。对于复杂场景可考虑使用Socket.io等封装库简化开发。

更多文章