前端WebSocket实时通信:别再用轮询了!

前端WebSocket实时通信:别再用轮询了!

毒舌时刻

WebSocket?听起来就像是前端工程师为了显得自己很专业而特意搞的一套复杂技术。你以为随便用个WebSocket就能实现实时通信?别做梦了!到时候你会发现,WebSocket连接断开的问题让你崩溃,重连机制让你晕头转向。

你以为WebSocket是万能的?别天真了!WebSocket在某些网络环境下会被防火墙拦截,而且服务器的负载也是个问题。还有那些所谓的WebSocket库,看起来高大上,用起来却各种问题。

为什么你需要这个

  1. 实时性:WebSocket提供全双工通信,可以实现真正的实时通信,比轮询更高效。
  2. 减少网络流量:WebSocket只需要建立一次连接,减少了HTTP请求的开销。
  3. 服务器推送:服务器可以主动向客户端推送数据,而不需要客户端轮询。
  4. 低延迟:WebSocket的延迟比轮询低,适合实时应用。
  5. 更好的用户体验:实时通信可以提供更好的用户体验,比如实时聊天、实时数据更新等。

反面教材

// 1. 简单WebSocket连接 const socket = new WebSocket('ws://localhost:8080'); socket.onopen = function(event) { console.log('WebSocket connected'); socket.send('Hello Server'); }; socket.onmessage = function(event) { console.log('Message from server:', event.data); }; socket.onclose = function(event) { console.log('WebSocket disconnected'); }; socket.onerror = function(error) { console.error('WebSocket error:', error); }; // 2. 缺少重连机制 const socket = new WebSocket('ws://localhost:8080'); socket.onclose = function(event) { console.log('WebSocket disconnected'); // 没有重连逻辑 }; // 3. 缺少心跳机制 const socket = new WebSocket('ws://localhost:8080'); // 没有心跳逻辑,连接可能会被服务器或网络设备断开 // 4. 消息处理混乱 const socket = new WebSocket('ws://localhost:8080'); socket.onmessage = function(event) { const message = JSON.parse(event.data); if (message.type === 'chat') { console.log('Chat message:', message.data); } else if (message.type === 'notification') { console.log('Notification:', message.data); } else if (message.type === 'update') { console.log('Update:', message.data); } }; // 5. 缺少错误处理 const socket = new WebSocket('ws://localhost:8080'); socket.onerror = function(error) { console.error('WebSocket error:', error); // 没有错误处理逻辑 }; 

问题

  • 简单WebSocket连接,缺少重连机制
  • 缺少心跳机制,连接可能会被断开
  • 消息处理混乱,难以维护
  • 缺少错误处理,遇到错误时无法恢复
  • 没有状态管理,难以追踪连接状态

正确的做法

基本WebSocket实现

// 1. 基本WebSocket连接 class WebSocketClient { constructor(url) { this.url = url; this.socket = null; this.connected = false; this.reconnectAttempts = 0; this.maxReconnectAttempts = 5; this.reconnectDelay = 1000; this.messageHandlers = {}; this.heartbeatInterval = null; } connect() { this.socket = new WebSocket(this.url); this.socket.onopen = (event) => { console.log('WebSocket connected'); this.connected = true; this.reconnectAttempts = 0; this.startHeartbeat(); }; this.socket.onmessage = (event) => { this.handleMessage(event.data); }; this.socket.onclose = (event) => { console.log('WebSocket disconnected'); this.connected = false; this.stopHeartbeat(); this.reconnect(); }; this.socket.onerror = (error) => { console.error('WebSocket error:', error); }; } reconnect() { if (this.reconnectAttempts < this.maxReconnectAttempts) { this.reconnectAttempts++; console.log(`Attempting to reconnect... (${this.reconnectAttempts}/${this.maxReconnectAttempts})`); setTimeout(() => { this.connect(); }, this.reconnectDelay * this.reconnectAttempts); } else { console.error('Max reconnect attempts reached'); } } startHeartbeat() { this.heartbeatInterval = setInterval(() => { if (this.connected) { this.send({ type: 'heartbeat' }); } }, 30000); // 30秒发送一次心跳 } stopHeartbeat() { if (this.heartbeatInterval) { clearInterval(this.heartbeatInterval); this.heartbeatInterval = null; } } send(data) { if (this.connected) { this.socket.send(JSON.stringify(data)); } else { console.error('WebSocket not connected'); } } on(type, handler) { if (!this.messageHandlers[type]) { this.messageHandlers[type] = []; } this.messageHandlers[type].push(handler); } handleMessage(data) { try { const message = JSON.parse(data); const { type, payload } = message; if (this.messageHandlers[type]) { this.messageHandlers[type].forEach(handler => { handler(payload); }); } } catch (error) { console.error('Error parsing message:', error); } } disconnect() { this.stopHeartbeat(); if (this.socket) { this.socket.close(); } } } // 使用 const wsClient = new WebSocketClient('ws://localhost:8080'); wsClient.connect(); // 监听消息 wsClient.on('chat', (payload) => { console.log('Chat message:', payload); }); wsClient.on('notification', (payload) => { console.log('Notification:', payload); }); // 发送消息 wsClient.send({ type: 'chat', payload: { message: 'Hello', user: 'John' } }); 

React中使用WebSocket

import React, { useEffect, useCallback, useRef, useState } from 'react'; function WebSocketComponent() { const [messages, setMessages] = useState([]); const [input, setInput] = useState(''); const wsClientRef = useRef(null); // 初始化WebSocket连接 useEffect(() => { wsClientRef.current = new WebSocketClient('ws://localhost:8080'); wsClientRef.current.connect(); // 监听消息 wsClientRef.current.on('chat', (payload) => { setMessages(prev => [...prev, payload]); }); // 清理函数 return () => { if (wsClientRef.current) { wsClientRef.current.disconnect(); } }; }, []); // 发送消息 const handleSend = useCallback(() => { if (input.trim() && wsClientRef.current) { wsClientRef.current.send({ type: 'chat', payload: { message: input, user: 'Current User' } }); setInput(''); } }, [input]); return ( <div> <div className="messages"> {messages.map((message, index) => ( <div key={index} className="message"> <strong>{message.user}:</strong> {message.message} </div> ))} </div> <div className="input-area"> <input type="text" value={input} onChange={(e) => setInput(e.target.value)} onKeyPress={(e) => e.key === 'Enter' && handleSend()} /> <button onClick={handleSend}>Send</button> </div> </div> ); } export default WebSocketComponent; 

高级WebSocket实现

// 1. 带认证的WebSocket class AuthWebSocketClient extends WebSocketClient { constructor(url, token) { super(url); this.token = token; } connect() { this.socket = new WebSocket(`${this.url}?token=${this.token}`); // 其他逻辑与WebSocketClient相同 } } // 2. 带重试机制的WebSocket class RetryWebSocketClient extends WebSocketClient { constructor(url, options = {}) { super(url); this.maxReconnectAttempts = options.maxReconnectAttempts || 10; this.reconnectDelay = options.reconnectDelay || 1000; this.exponentialBackoff = options.exponentialBackoff || true; } reconnect() { if (this.reconnectAttempts < this.maxReconnectAttempts) { this.reconnectAttempts++; const delay = this.exponentialBackoff ? this.reconnectDelay * Math.pow(2, this.reconnectAttempts - 1) : this.reconnectDelay; console.log(`Attempting to reconnect... (${this.reconnectAttempts}/${this.maxReconnectAttempts})`); setTimeout(() => { this.connect(); }, delay); } else { console.error('Max reconnect attempts reached'); } } } // 3. 消息队列 class QueueWebSocketClient extends WebSocketClient { constructor(url) { super(url); this.messageQueue = []; } connect() { super.connect(); this.socket.onopen = (event) => { console.log('WebSocket connected'); this.connected = true; this.reconnectAttempts = 0; this.startHeartbeat(); // 发送队列中的消息 this.flushQueue(); }; } send(data) { if (this.connected) { this.socket.send(JSON.stringify(data)); } else { // 将消息加入队列 this.messageQueue.push(data); console.log('WebSocket not connected, message queued'); } } flushQueue() { if (this.connected && this.messageQueue.length > 0) { console.log(`Flushing ${this.messageQueue.length} queued messages`); this.messageQueue.forEach(message => { this.socket.send(JSON.stringify(message)); }); this.messageQueue = []; } } } 

最佳实践

// 1. WebSocket服务端实现(Node.js) const WebSocket = require('ws'); const server = new WebSocket.Server({ port: 8080 }); const clients = new Set(); server.on('connection', (socket) => { console.log('Client connected'); clients.add(socket); // 发送欢迎消息 socket.send(JSON.stringify({ type: 'system', payload: 'Welcome to the WebSocket server!' })); // 处理消息 socket.on('message', (message) => { try { const parsedMessage = JSON.parse(message); console.log('Received message:', parsedMessage); // 处理心跳 if (parsedMessage.type === 'heartbeat') { socket.send(JSON.stringify({ type: 'heartbeat' })); return; } // 广播消息 clients.forEach(client => { if (client.readyState === WebSocket.OPEN) { client.send(JSON.stringify(parsedMessage)); } }); } catch (error) { console.error('Error parsing message:', error); } }); // 处理断开连接 socket.on('close', () => { console.log('Client disconnected'); clients.delete(socket); }); // 处理错误 socket.on('error', (error) => { console.error('Socket error:', error); }); }); console.log('WebSocket server running on port 8080'); // 2. 前端WebSocket管理 class WebSocketManager { static instance = null; constructor() { this.clients = {}; } static getInstance() { if (!WebSocketManager.instance) { WebSocketManager.instance = new WebSocketManager(); } return WebSocketManager.instance; } createClient(name, url, options = {}) { const client = new QueueWebSocketClient(url, options); this.clients[name] = client; client.connect(); return client; } getClient(name) { return this.clients[name]; } removeClient(name) { if (this.clients[name]) { this.clients[name].disconnect(); delete this.clients[name]; } } disconnectAll() { Object.values(this.clients).forEach(client => { client.disconnect(); }); this.clients = {}; } } // 使用 const wsManager = WebSocketManager.getInstance(); const chatClient = wsManager.createClient('chat', 'ws://localhost:8080'); const notificationClient = wsManager.createClient('notification', 'ws://localhost:8080'); // 3. 错误处理和监控 class MonitoredWebSocketClient extends WebSocketClient { constructor(url) { super(url); this.errorCount = 0; this.maxErrorCount = 10; } handleError(error) { this.errorCount++; console.error('WebSocket error:', error); if (this.errorCount > this.maxErrorCount) { console.error('Max error count reached, disconnecting'); this.disconnect(); } } socket.onerror = (error) => { this.handleError(error); }; } 

毒舌点评

WebSocket确实很重要,但我见过太多开发者滥用这个特性,导致应用变得过于复杂。

想象一下,当你为了实现实时通信,使用了WebSocket,结果发现服务器负载过高,这真的值得吗?

还有那些过度使用WebSocket的开发者,为了实时性而使用WebSocket,结果发现轮询可能更加适合他们的场景。

所以,在使用WebSocket时,一定要根据实际需求来决定。不要为了使用WebSocket而使用,要选择最适合的方案。

当然,对于需要实时通信的应用来说,WebSocket是必要的。但对于不需要实时性的应用,轮询可能更加简单和可靠。

最后,记住一句话:WebSocket的目的是为了实现实时通信,而不是为了炫技。如果你的WebSocket实现导致应用变得更复杂或更不可靠,那你就失败了。

Read more

PX4无人机|MID360使用FAST_LIO,实现自主飞行及定点——PX4无人机配置流程(六)

PX4无人机|MID360使用FAST_LIO,实现自主飞行及定点——PX4无人机配置流程(六)

PX4固件版本为1.15.4 qgc地面站版本为4.4.5 飞控,使用微空科技MicoAir743V2 机载电脑:12代i5,ubuntu20.04 安装位置:mid360的接口对应飞机的后方 推荐阅读px4+vio实现无人机室内定位_px4+室内视觉定位-ZEEKLOG博客 和飞控连接机载电脑相关,有用 代码参考: PX4|基于FAST-LIO mid360的无人机室内自主定位及定点悬停_fastlio mid360-ZEEKLOG博客 使用视觉或动作捕捉系统进行位置估计 | PX4 指南(主) --- Using Vision or Motion Capture Systems for Position Estimation | PX4 Guide (main) 一.px4飞控设置 建议看官方文档:Using Vision or Motion

数字频率计设计在FPGA上的优化策略

FPGA上的数字频率计设计:从原理到实战的系统优化 你有没有遇到过这样的场景?手头有个信号发生器,输出一个未知频率的方波,想快速测出它的频率。用万用表?不行,普通万用表不支持高频测量。拿示波器看周期?可以,但操作繁琐、响应慢。这时候,一台高精度、响应快的 数字频率计 就显得尤为重要。 而在现代电子系统中,基于FPGA实现的数字频率计,正逐渐取代传统单片机或专用IC方案,成为高性能测量设备的核心选择。为什么?因为FPGA不仅具备并行处理能力,还能灵活重构逻辑结构,尤其适合对实时性、精度和动态范围都有严苛要求的应用。 但问题来了: 有了FPGA,是不是随便写个计数器就能搞定频率测量? 答案是否定的。 很多初学者在FPGA上做频率计时,常犯几个致命错误:直接把待测信号当钟用、跨时钟域数据没同步、低频误差大得离谱……结果要么烧板子,要么测不准,甚至系统频繁崩溃。 本文将带你深入剖析 数字频率计在FPGA平台上的完整设计链条 ,从基础原理出发,聚焦实际工程中的关键瓶颈,提出一套可落地的优化策略。我们不堆术语,只讲“人话”;不罗列理论,只谈你在调试时真正会踩的坑和对应的解法。 闸门

飞书机器人实战:5分钟搞定图片消息发送(含常见报错解决方案)

飞书机器人实战:5分钟搞定图片消息发送(含常见报错解决方案) 你是否遇到过这样的场景:服务器监控系统捕捉到一个异常峰值,你希望它能自动将一张清晰的图表截图,直接推送到团队的飞书群里,而不是一封冰冷的邮件;或者,你的自动化日报系统生成了精美的数据可视化图片,你希望它能无缝地出现在每日的晨会通知中。对于许多开发者和运维工程师来说,将图片消息集成到自动化流程中,是一个能极大提升信息传达效率和体验的“刚需”。 飞书机器人提供了强大的消息推送能力,但初次接触其图片消息发送功能时,你可能会发现它比预想的要“曲折”一些——它不像发送文本那样直接丢一个图片链接就行,而是需要经过一个“上传-获取密钥-发送”的流程。这个过程里,权限配置、tenant_access_token获取、图片上传格式、image_key的使用,每一步都可能藏着一个小坑。别担心,这篇文章就是为你准备的“避坑指南”。我们将抛开官方文档那略显冰冷的步骤罗列,从一个实战者的角度,带你用大约5分钟的时间,彻底打通从零到一发送飞书图片消息的全链路,并重点剖析那些你可能马上就会遇到的报错及其根因解决方案。我们的目标是:让你看完就能用,用了

【大模型应用篇】用 OpenClaw + 飞书打造 7x24 小时服务器运维机器人

【大模型应用篇】用 OpenClaw + 飞书打造 7x24 小时服务器运维机器人

前言 本文基于OpenClaw,也是最近超火的可在本地运行的AI Agent网关,记录从零搭建通过飞书对话管理服务器运维机器人的全过程。该机器人支持随时随地通过飞书查看服务器状态、检索日志、管理进程,其核心机制在于:由OpenClaw将聊天平台(飞书等)的消息路由至大模型,模型调用本地工具(如Shell、文件系统、浏览器)执行相应任务,最终将结果自动返回至飞书会话中,实现自动化运维交互。 架构概览 飞书 App (WebSocket 长连接)         ↕ OpenClaw Gateway (服务器上 systemd 常驻)         ↕ AI 模型 (DeepSeek v3.2/GLM 4.7)         ↕ 服务器 Shell (受白名单限制的命令执行) 核心组件: * OpenClaw Gateway:Agent 网关,管理会话、工具调用、渠道连接 * 飞书插件:通过