当前位置: 首页 > Skill >

WebSocket

WebSocket

1.0.0 2026.11.27 浏览:366
获取Skill文件查看使用说明
作者:叶澄许可证:
本文目录展开

Reconnection (Always Forget)

  • Connections drop silently—TCP FIN may never arrive; don't assume onclose fires
  • Exponential backoff: 1s, 2s, 4s, 8s... cap at 30s—prevents thundering herd on server recovery
  • Add jitter: delay * (0.5 + Math.random())—prevents synchronized reconnection storms
  • Track reconnection state—queue messages during reconnect, replay after
  • Max retry limit then surface error to user—don't retry forever silently

Heartbeats (Critical)

  • Ping/pong frames at protocol level—browser doesn't expose; use application-level ping
  • Send ping every 30s, expect pong within 10s—no pong = connection dead, reconnect
  • Server should ping too—detects dead clients, cleans up resources
  • Idle timeout in proxies (60-120s typical)—heartbeat must be more frequent
  • Don't rely on TCP keepalive—too infrequent, not reliable through proxies

Connection State

  • readyState: 0=CONNECTING, 1=OPEN, 2=CLOSING, 3=CLOSED—check before sending
  • Buffer messages while CONNECTING—send after OPEN
  • bufferedAmount shows queued bytes—pause sending if backpressure building
  • Multiple tabs = multiple connections—coordinate via BroadcastChannel or SharedWorker

Authentication

  • Token in URL query: wss://host/ws?token=xxx—simple but logged in access logs
  • First message auth: connect, send token, wait for ack—cleaner but more round trips
  • Cookie auth: works if same origin—but no custom headers in WebSocket
  • Reauthenticate after reconnect—don't assume previous session valid

Scaling Challenges

  • WebSocket connections are stateful—can't round-robin between servers
  • Sticky sessions: route by client ID to same server—or use Redis pub/sub for broadcast
  • Each connection holds memory—thousands of connections = significant RAM
  • Graceful shutdown: send close frame, wait for clients to reconnect elsewhere

Nginx/Proxy Config

proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 3600s;
  • Without these headers, upgrade fails—connection closes immediately
  • proxy_read_timeout must exceed your ping interval—default 60s too short
  • Load balancer health checks: separate HTTP endpoint, not WebSocket

Close Codes

  • 1000: normal closure; 1001: going away (page close)
  • 1006: abnormal (no close frame received)—usually network issue
  • 1008: policy violation; 1011: server error
  • 4000-4999: application-defined—use for auth failure, rate limit, etc.
  • Always send close code and reason—helps debugging

Message Handling

  • Text frames for JSON; binary frames for blobs/protobuf—don't mix without framing
  • No guaranteed message boundaries in TCP—but WebSocket handles framing for you
  • Order preserved per connection—messages arrive in send order
  • Large messages may fragment—library handles reassembly; set max message size server-side

Security

  • Validate Origin header on handshake—prevent cross-site WebSocket hijacking
  • Same-origin policy doesn't apply—any page can connect to your WebSocket server
  • Rate limit per connection—one client can flood with messages
  • Validate every message—malicious clients can send anything after connecting

Common Mistakes

  • No heartbeat—connection appears alive but is dead; messages go nowhere
  • Reconnect without backoff—hammers server during outage, prolongs recovery
  • Storing state only in connection—lost on reconnect; persist critical state externally
  • Huge messages—blocks event loop; stream large data via chunking
  • Not handling bufferedAmount—memory grows unbounded if client slower than server

相关文章

更多
基于Swoole扩展的PHP WebSocket服务端实现示例

本文展示如何利用Swoole扩展在PHP中构建WebSocket服务端。通过继承Swoole\Network\Protocol\WebSocket类,开发者可以自定义onClose和onMessage事件处理逻辑,实现用户下线通知及消息广播功能。结合Server实例配置与协议加载,即可快速搭建支持多客户端通信的基础服务架构。

2025.04.17 778
高并发下PHP WebSocket服务端的内存优化与性能调优

通过 Swoole 的协程特性与连接池管理,配合内存监控脚本定期清理僵尸连接,可将高并发下的 WebSocket 服务端内存占用降低至稳定水平。

2025.12.14 731
PHP WebSocket服务端广播消息与房间管理实现

使用 Swoole 的 WebSocket 服务器实现广播与房间管理,核心在于连接建立时注册用户到房间数组,推送消息时遍历目标房间内的 $server->connections 进行发送。

2026.10.04 541
Workerman框架下PHP WebSocket服务端搭建与消息推送

在 Workerman 中实现 WebSocket 推送,核心是继承 Worker 类并处理 onMessage 事件。服务端启动后监听端口,客户端连接时触发 onConnect ,发送消息时触发 onMessage ,此时通过 $worker->connections 遍历所有活跃连接进行广播,或指定 $connec

2025.04.19 530
PHP WebSocket服务端怎么正确接收与发送二进制数据

在 PHP WebSocket 服务端处理二进制数据时,核心难点在于区分文本帧与二进制帧的 opcode ,并正确处理客户端发送的掩码( Mask )数据。若直接使用标准库或简单封装而未对 opcode 0 x2 进行专门解析,往往会导致数据乱码或接收失败。正确的做法是监听 onMessage 事件,判断帧类型是否为二

2025.09.01 362
Skill 文件
  • SKILL.md
    • Reconnection (Always Forget)
    • Heartbeats (Critical)
    • Connection State
    • Authentication
    • Scaling Challenges
    • Nginx/Proxy Config
    • Close Codes
    • Message Handling
    • Security
    • Common Mistakes
  • 项目或源文件

相关 Skill

更多
Websocket Patterns Websocket Patterns 深度 WebSocket/SSE工作流——握手与认证、会话生命周期、心跳、顺序、背压、扩展及可观测性,适用于实时系统构建。
service-qa-coach service-qa-coach Review support quality for chat, email, phone, social DM, or marketplace service teams. Use when a team needs a QA scorecard, failure-mode analysis, coaching plan, calibration checklist, or service-improvement brief without live ticketing, CRM, or contact-center system access.
高中数学作业批改助手 高中数学作业批改助手 >图片识别 直接读取学生手写作答照片,识别公式、符号、步骤 🧮 自动推导 根据题目自动生成参考答案和评分细则,无需教师预设 📊 逐步给分 每个关键步骤独立评分,体现过程分 📝 结构化报告 输出含识别内容、参考答案、逐步评分、改进建议的完整报告 🗂 批量批改 支持一次性批改多道题,最终汇总得分表
Vibration Analysis Vibration Analysis 分析来自CMS趋势、RMS/峰值、频谱及SCADA报警的风机传动链(主轴、齿轮箱、发电机)振动数据。
Traditional Bone Tool Making Basics Traditional Bone Tool Making Basics Use when you need custom, durable, repairable tools like awls, needles, scrapers, harpoons, or fishing hooks made from local animal bones or antlers and comm...