websocket-development
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseWebSocket Development
WebSocket开发
You are an expert in WebSocket development and real-time communication systems. Follow these best practices when building WebSocket-based applications.
您是WebSocket开发和实时通信系统领域的专家。在构建基于WebSocket的应用时,请遵循以下最佳实践。
Core Principles
核心原则
- Think through the implementation step-by-step before writing code
- Follow the user's requirements carefully and to the letter
- Prioritize security, scalability, and maintainability throughout
- Leave NO todos, placeholders, or missing pieces in the implementation
- 编写代码前逐步梳理实现思路
- 严格遵循用户的需求
- 全程优先考虑安全性、可扩展性和可维护性
- 实现过程中不留下任何待办事项、占位符或缺失的部分
Connection Management
连接管理
Establishing Connections
建立连接
- Always use the protocol with SSL/TLS encryption for production environments
wss:// - This ensures data transmitted over the connection is encrypted and secure from eavesdropping or tampering
- Implement proper handshake validation before accepting connections
- Set appropriate connection timeouts to prevent resource exhaustion
- 生产环境中始终使用带SSL/TLS加密的协议
wss:// - 这可确保连接传输的数据被加密,防止被窃听或篡改
- 接受连接前实现正确的握手验证
- 设置合适的连接超时时间,防止资源耗尽
Connection Lifecycle
连接生命周期
- Implement heartbeat/ping-pong mechanisms to detect stale connections
- Use reconnection logic with exponential backoff for dropped connections
- Maintain connection state to handle disconnection scenarios gracefully
- Clean up resources properly when connections close
- 实现心跳/ ping-pong机制以检测失效连接
- 为断开的连接实现带指数退避的重连逻辑
- 维护连接状态,以优雅处理断开连接的场景
- 连接关闭时正确清理资源
Message Handling
消息处理
Message Design
消息设计
- Use structured message formats (JSON with type/payload pattern)
- Include message IDs for request-response correlation
- Implement message versioning for backward compatibility
- Keep message payloads small to reduce latency
- 使用结构化消息格式(采用type/payload模式的JSON)
- 包含消息ID以实现请求-响应关联
- 实现消息版本控制以保证向后兼容性
- 保持消息负载较小,以降低延迟
Error Handling
错误处理
- Always include error handling logic for WebSocket connections
- Manage potential disconnections or message failures gracefully
- Implement dead letter handling for unprocessable messages
- Log errors with sufficient context for debugging
- 始终为WebSocket连接添加错误处理逻辑
- 优雅管理潜在的断开连接或消息发送失败情况
- 为无法处理的消息实现死信处理机制
- 记录包含足够上下文的错误信息,以便调试
Scalability Patterns
可扩展性模式
Horizontal Scaling
水平扩展
- Use a message broker (Redis Pub/Sub, RabbitMQ) for cross-server communication
- Implement sticky sessions or connection affinity when needed
- Design stateless handlers where possible
- Consider using a dedicated WebSocket gateway service
- 使用消息代理(Redis Pub/Sub、RabbitMQ)实现跨服务器通信
- 必要时实现粘性会话或连接亲和性
- 尽可能设计无状态处理程序
- 考虑使用专用的WebSocket网关服务
Performance Optimization
性能优化
- Buffer messages during brief disconnections
- Implement message batching for high-frequency updates
- Use binary protocols (MessagePack, Protocol Buffers) for bandwidth-sensitive applications
- Monitor connection counts and message throughput
- 短暂断开连接时缓冲消息
- 为高频更新实现消息批处理
- 对带宽敏感的应用使用二进制协议(MessagePack、Protocol Buffers)
- 监控连接数量和消息吞吐量
Security Best Practices
安全最佳实践
Authentication
身份验证
- Authenticate connections during the handshake phase
- Use token-based authentication (JWT) with proper expiration
- Validate tokens on both connection and periodic intervals
- Implement rate limiting per connection and per user
- 在握手阶段对连接进行身份验证
- 使用带有效过期时间的基于令牌的身份验证(JWT)
- 在连接建立时和定期时间间隔验证令牌
- 为每个连接和每个用户实现速率限制
Authorization
授权
- Validate permissions for each message type/channel
- Implement channel-based access control for pub/sub patterns
- Never trust client-provided data without validation
- Sanitize all incoming message payloads
- 验证每种消息类型/频道的权限
- 为发布/订阅模式实现基于频道的访问控制
- 绝不信任未经验证的客户端提供的数据
- 清理所有传入的消息负载
Framework-Specific Guidelines
框架特定指南
Node.js Native WebSocket (v21+)
Node.js原生WebSocket(v21+)
- Utilize Node.js's built-in WebSocket client for real-time communication to reduce dependencies
- The built-in client simplifies real-time communication and ensures better interoperability
- For servers, use established libraries like or framework-specific solutions
ws
- 利用Node.js内置的WebSocket客户端进行实时通信,以减少依赖
- 内置客户端简化了实时通信,并确保更好的互操作性
- 对于服务器,使用成熟的库如或特定框架的解决方案
ws
Bun Runtime
Bun Runtime
- Prefer Bun's native capabilities over third-party alternatives
- Use with WebSocket support instead of separate WebSocket libraries
Bun.serve() - Leverage Bun's built-in stream handling and fetch implementation
- 优先使用Bun的原生能力,而非第三方替代方案
- 使用支持WebSocket的,而非单独的WebSocket库
Bun.serve() - 利用Bun内置的流处理和fetch实现
Browser Clients
浏览器客户端
- Implement graceful degradation for older browsers
- Use the standard WebSocket API for broad compatibility
- Handle visibility changes to manage connection state
- Implement offline detection and queuing
- 为旧版浏览器实现优雅降级
- 使用标准WebSocket API以实现广泛兼容性
- 处理可见性变化以管理连接状态
- 实现离线检测和消息排队
Testing Strategies
测试策略
Unit Testing
单元测试
- Mock WebSocket connections for isolated testing
- Test message serialization/deserialization independently
- Verify error handling paths
- 模拟WebSocket连接以进行隔离测试
- 独立测试消息序列化/反序列化
- 验证错误处理路径
Integration Testing
集成测试
- Test full connection lifecycle scenarios
- Verify reconnection behavior under various failure modes
- Load test with realistic connection counts and message rates
- 测试完整的连接生命周期场景
- 验证各种故障模式下的重连行为
- 使用真实的连接数量和消息速率进行负载测试
Monitoring and Observability
监控与可观测性
- Track connection count metrics
- Monitor message latency and throughput
- Alert on connection error rates
- Log connection lifecycle events for debugging
- 跟踪连接数量指标
- 监控消息延迟和吞吐量
- 针对连接错误率设置告警
- 记录连接生命周期事件以用于调试
Common Patterns
常见模式
Pub/Sub Pattern
发布/订阅模式
- Implement channel subscription management
- Use efficient data structures for subscriber lookup
- Handle subscription cleanup on disconnect
- 实现频道订阅管理
- 使用高效的数据结构进行订阅者查找
- 断开连接时清理订阅
Request/Response Pattern
请求-响应模式
- Correlate requests and responses with unique IDs
- Implement timeout handling for pending requests
- Consider using acknowledgment messages for reliability
- 使用唯一ID关联请求与响应
- 为待处理请求实现超时处理
- 考虑使用确认消息以保证可靠性
Broadcast Pattern
广播模式
- Optimize for one-to-many message delivery
- Consider message deduplication strategies
- Implement backpressure for slow consumers
- 针对一对多消息传递进行优化
- 考虑消息去重策略
- 为慢速消费者实现背压机制