前端——别再轮询了!手摸手教你用WebSocket打造实时应用,面试必问

张开发
2026/4/17 5:20:31 15 分钟阅读

分享文章

前端——别再轮询了!手摸手教你用WebSocket打造实时应用,面试必问
引言你有没有遇到过这样的场景用户抱怨直播间弹幕延迟好几秒、消息收不到、在线人数显示不准… 而你明明用的是轮询每秒请求一次服务器都快扛不住了。这不是段子这是我去年接手一个项目时的真实写照。轮询这个看似简单的方案在并发量上来后就成了灾难。今天我就来聊聊如何用WebSocket彻底解决实时通信问题。读完这篇文章你将收获✅ WebSocket连接管理的完整封装✅ 自动重连机制的实现含指数退避✅ Vue/Vuex中集成WebSocket的最佳实践✅ 生产环境踩坑总结附解决方案一、轮询为什么不行先看一组真实数据来自我优化前的项目指标轮询方案长连接方案消息延迟1-3秒100毫秒服务器QPS60次/分钟/用户1次连接/用户带宽消耗高极低实时性❌ 差✅ 优移动端兼容❌ 耗电✅ 省电结论轮询只适合低实时性场景直播间这种场景必须上长连接。二、WebSocket连接管理器封装先看一个生产可用的连接管理器javascript// utils/websocket.js class WebSocketManager { constructor(url, options {}) { this.url url this.reconnectInterval options.reconnectInterval || 5000 this.maxReconnectAttempts options.maxReconnectAttempts || 5 this.reconnectAttempts 0 this.eventHandlers {} this.ws null this.heartbeatTimer null } connect() { return new Promise((resolve, reject) { try { this.ws new WebSocket(this.url) this.ws.onopen (event) { console.log(WebSocket连接已建立) this.reconnectAttempts 0 this.startHeartbeat() this.emit(open, event) resolve() } this.ws.onmessage (event) { const data JSON.parse(event.data) // 处理心跳响应 if (data.type pong) { return } this.emit(message, data) } this.ws.onerror (event) { console.error(WebSocket发生错误, event) this.emit(error, event) reject(event) } this.ws.onclose (event) { console.log(WebSocket连接已关闭, event) this.stopHeartbeat() this.emit(close, event) this.attemptReconnect() } } catch (error) { reject(error) } }) } // 心跳保活 startHeartbeat() { this.heartbeatTimer setInterval(() { if (this.ws this.ws.readyState WebSocket.OPEN) { this.ws.send(JSON.stringify({ type: ping })) } }, 30000) } stopHeartbeat() { if (this.heartbeatTimer) { clearInterval(this.heartbeatTimer) this.heartbeatTimer null } } // 指数退避重连 attemptReconnect() { if (this.reconnectAttempts this.maxReconnectAttempts) { const delay Math.min(1000 * Math.pow(2, this.reconnectAttempts), 30000) console.log(${delay}ms后进行第${this.reconnectAttempts 1}次重连) setTimeout(() { this.reconnectAttempts this.connect() }, delay) } else { console.error(达到最大重连次数停止重连) this.emit(reconnect-failed) } } send(data) { if (this.ws this.ws.readyState WebSocket.OPEN) { this.ws.send(JSON.stringify(data)) } else { console.warn(WebSocket未连接消息已缓存) this.cacheMessage(data) } } cacheMessage(data) { // 实现离线消息缓存 if (!this.pendingMessages) { this.pendingMessages [] } this.pendingMessages.push(data) } flushPendingMessages() { if (this.pendingMessages this.ws.readyState WebSocket.OPEN) { this.pendingMessages.forEach(msg this.send(msg)) this.pendingMessages [] } } on(event, handler) { if (!this.eventHandlers[event]) { this.eventHandlers[event] [] } this.eventHandlers[event].push(handler) } off(event, handler) { if (this.eventHandlers[event]) { const index this.eventHandlers[event].indexOf(handler) if (index -1) { this.eventHandlers[event].splice(index, 1) } } } emit(event, data) { if (this.eventHandlers[event]) { this.eventHandlers[event].forEach(handler handler(data)) } } close() { this.stopHeartbeat() if (this.ws) { this.ws.close() } } } export default WebSocketManager这段代码包含3个核心能力自动重连指数退避算法避免频繁请求心跳保活30秒发送ping检测连接健康离线缓存断网时的消息不丢失三、Vue组件中如何使用vuetemplate div classlive-room div classroom-header h2{{ roomInfo.title }}/h2 span classonline-count {{ viewerCount }}人在线/span /div div classchat-area refchatArea div v-formsg in messages :keymsg.id classmessage :class{ my-message: msg.isSelf } img :srcmsg.avatar classavatar / div classcontent span classusername{{ msg.username }}/span span classtext{{ msg.content }}/span /div /div /div div classinput-area input v-modelinputMessage keyup.entersendMessage placeholder说点什么... / button clicksendMessage发送/button /div !-- 连接状态指示器 -- div classconnection-status :classconnectionStatus {{ statusText }} /div /div /template script import WebSocketManager from /utils/websocket export default { name: LiveRoom, data() { return { wsManager: null, roomInfo: {}, viewerCount: 0, messages: [], inputMessage: , connectionStatus: connecting, // connecting, connected, disconnected maxMessageCount: 200 } }, computed: { statusText() { const map { connecting: 连接中..., connected: 已连接, disconnected: 连接断开正在重连... } return map[this.connectionStatus] } }, async mounted() { await this.initWebSocket() this.joinRoom() }, beforeDestroy() { this.cleanup() }, methods: { async initWebSocket() { this.wsManager new WebSocketManager(wss://api.example.com/ws) this.wsManager.on(open, () { this.connectionStatus connected this.wsManager.flushPendingMessages() }) this.wsManager.on(message, this.handleMessage) this.wsManager.on(close, () { this.connectionStatus disconnected }) this.wsManager.on(reconnect-failed, () { this.$toast.error(连接失败请刷新页面重试) }) await this.wsManager.connect() }, joinRoom() { this.wsManager.send({ type: JOIN_ROOM, roomId: this.$route.params.roomId, userId: this.$store.state.user.id }) }, handleMessage(data) { switch (data.type) { case ROOM_INFO: this.roomInfo data.payload break case VIEWER_COUNT: this.viewerCount data.payload.count break case CHAT_MESSAGE: this.addMessage(data.payload) break case ERROR: this.$toast.error(data.message) break } }, addMessage(message) { this.messages.push(message) // 限制消息数量防止内存溢出 if (this.messages.length this.maxMessageCount) { this.messages this.messages.slice(-this.maxMessageCount) } this.scrollToBottom() }, sendMessage() { if (!this.inputMessage.trim()) return this.wsManager.send({ type: CHAT_MESSAGE, content: this.inputMessage, roomId: this.$route.params.roomId }) this.inputMessage }, scrollToBottom() { this.$nextTick(() { const area this.$refs.chatArea if (area) { area.scrollTop area.scrollHeight } }) }, cleanup() { if (this.wsManager) { this.wsManager.off(message, this.handleMessage) this.wsManager.close() } } } } /script style scoped .connection-status { position: fixed; top: 10px; right: 10px; padding: 4px 12px; border-radius: 20px; font-size: 12px; } .connection-status.connecting { background: #f39c12; color: #fff; } .connection-status.connected { background: #27ae60; color: #fff; } .connection-status.disconnected { background: #e74c3c; color: #fff; animation: pulse 1s infinite; } keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.6; } } /style四、Vuex集成推荐大型项目javascript// store/modules/realtime.js import WebSocketManager from /utils/websocket const state { wsConnected: false, roomStats: { viewers: 0, likes: 0, giftTotal: 0 }, messageQueue: [], unreadCount: 0 } const mutations { SET_WS_STATUS(state, status) { state.wsConnected status }, UPDATE_STATS(state, stats) { state.roomStats { ...state.roomStats, ...stats } }, PUSH_MESSAGE(state, message) { state.messageQueue.push(message) state.unreadCount // 限制队列长度 if (state.messageQueue.length 500) { state.messageQueue.shift() } }, CLEAR_UNREAD(state) { state.unreadCount 0 } } const actions { initWebSocket({ commit, dispatch }) { const ws new WebSocketManager(wss://api.example.com/realtime) ws.on(open, () { commit(SET_WS_STATUS, true) dispatch(sendJoinMessage) }) ws.on(message, (data) { switch (data.type) { case STATS_UPDATE: commit(UPDATE_STATS, data.payload) break case NEW_MESSAGE: commit(PUSH_MESSAGE, data.payload) break } }) ws.on(close, () { commit(SET_WS_STATUS, false) }) return ws.connect() } } export default { namespaced: true, state, mutations, actions }五、生产环境踩坑总结坑1移动端WebSocket自动断开现象App切到后台再回来连接已断开原因手机系统省电策略会挂起后台应用解决方案javascript// 监听页面可见性变化 document.addEventListener(visibilitychange, () { if (document.visibilityState visible) { // 页面重新可见检查并重连 if (!wsManager.isConnected()) { wsManager.connect() } } })坑2Nginx代理WebSocket超时现象连接1分钟后自动断开原因Nginx默认60秒无数据交互会断开解决方案Nginx配置nginxlocation /ws/ { proxy_pass http://backend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection upgrade; proxy_read_timeout 3600s; # 改为1小时 proxy_send_timeout 3600s; }坑3负载均衡导致连接飘移现象消息收不到或者重复收到原因多台服务器之间没有共享连接状态解决方案方案A使用Redis Pub/Sub同步消息方案B使用IP Hash负载均衡策略方案C使用成熟的Socket.io自带降级和粘性会话六、什么时候该用WebSocket场景推荐方案理由直播间弹幕✅ WebSocket高并发、低延迟消息通知✅ WebSocket实时性要求高在线协作文档✅ WebSocket双向同步股票行情✅ WebSocket数据实时性强用户行为统计❌ 轮询/上报丢一些数据影响不大配置拉取❌ HTTP变更频率低写在最后WebSocket并不是银弹它的维护成本比轮询高但在需要实时性的场景下它是绕不开的选择。这篇文章的代码已经在我最近的项目中稳定运行了3个月支撑了日均百万级的消息量。如果你正在做一个实时性要求高的项目希望这篇文章能帮到你。

更多文章