当前位置: 首页 > Skill >

Websocket Patterns

Websocket Patterns

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

WebSocket Patterns (Deep Workflow)

Realtime connections add stateful complexity: who is connected, what order messages arrive, and what happens when links flap. Design for at-least-once delivery, explicit heartbeats, and horizontal scaling early.

When to Offer This Workflow

Trigger conditions:

  • Replacing polling with WS or SSE
  • Auth on connect; token refresh mid-session
  • Fan-out to many subscribers; presence and typing indicators
  • Sticky sessions, load balancer timeouts, reconnect storms

Initial offer:

Use six stages: (1) choose transport, (2) connection & auth, (3) protocol & messages, (4) reliability & ordering, (5) scale & ops, (6) security & abuse). Confirm browser vs server clients and proxies (nginx, ALB, Cloudflare).

Stage 1: Choose Transport

Goal: WebSocket vs SSE vs long polling—right tool per direction.

Heuristics

  • Bidirectional, low latency, binary payloads → WebSocket
  • Server → client one-way streams, HTTP-friendly infra → SSE
  • Fire-and-forget notifications with simple infra → consider push services first

Caveats

  • Corporate proxies historically hurt WS—test environments; WSS mandatory
  • HTTP/3 QUIC stacks differ—validate intermediaries

Exit condition: Transport choice documented with why not alternatives.

Stage 2: Connection & Auth

Goal: Authenticated sockets without long-lived secrets in query strings when avoidable.

Patterns

  • JWT in Sec-WebSocket-Protocol or first message after connect—prefer short-lived tokens + refresh flow
  • Cookie sessions with CSRF considerations on same-site policies
  • Re-auth before token expiry; graceful close with code and reason

Authorization

  • Subscribe to topics only after server-side check—never trust client channel names alone

Exit condition: Auth diagram: issue token → connect → authorize subscriptions.

Stage 3: Protocol & Messages

Goal: Versioned message schema; predictable errors.

Design

  • Envelope: { type, id, ts, payload }; correlation ids for RPC-style
  • Version negotiation on connect or feature flags in hello message
  • Binary vs JSON—protobuf/msgpack for bandwidth; JSON for debuggability early

Heartbeats

  • Ping/pong or application-level heartbeat at interval < proxy timeout (often 30–60s)
  • Idle detection and clean disconnect

Exit condition: Protocol doc + example session transcript.

Stage 4: Reliability & Ordering

Goal: Define delivery semantics—usually at-least-once over TCP; ordering per channel.

Practices

  • Idempotent message handlers; dedupe by message id when retries exist
  • Per-user sequence numbers if strict order matters
  • Buffer limits: drop, close, or apply backpressure policy

Reconnect

  • Exponential backoff + jitter to prevent thundering herd
  • Resume from last seen seq if missed messages are unacceptable—persist or snapshot

Exit condition: Reconnect story documented; storm mitigation tested.

Stage 5: Scale & Operations

Goal: Many connections across many nodes—affinity and pub/sub backbone.

Architecture

  • Sticky sessions or shared pub/sub (Redis, NATS, Kafka) for cross-node fan-out
  • Shard connection maps; avoid single giant in-memory map on one box

Observability

  • Metrics: active connections, msg/sec, queue depth, disconnect reasons
  • Tracing: connect → subscribe → first message latency

Load shedding

  • Max connections per IP/user; rate limit connection attempts

Exit condition: Capacity model: connections per node × message fan-out cost.

Stage 6: Security & Abuse

Goal: Minimize attack surface on long-lived pipes.

Controls

  • WSS everywhere; validate Origin where applicable
  • Payload size limits; compression bomb awareness
  • AuthZ on every subscription; audit admin actions

Abuse

  • Spam detection; kick/ban flows; circuit breakers on misbehaving clients

Final Review Checklist

  • Transport choice justified (WS/SSE/etc.)
  • AuthN/Z on connect and per-channel
  • Heartbeats aligned with proxy/LB timeouts
  • Delivery/idempotency/reconnect semantics explicit
  • Horizontal scale path + observability + abuse controls

Tips for Effective Guidance

  • ALB idle timeout vs heartbeat—classic production bug; call it out.
  • When user says “real-time,” ask latency target and ordering needs.
  • SSE is simpler—don’t default to WS for one-way feeds.

Handling Deviations

  • Edge runtimes (Workers): different connection limits and duration—validate platform.
  • Mobile: background suspension—push notifications may complement WS.

相关文章

更多
基于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
    • WebSocket Patterns (Deep Workflow)
    • When to Offer This Workflow
    • Stage 1: Choose Transport
      • Heuristics
      • Caveats
    • Stage 2: Connection & Auth
      • Patterns
      • Authorization
    • Stage 3: Protocol & Messages
      • Design
      • Heartbeats
    • Stage 4: Reliability & Ordering
      • Practices
      • Reconnect
    • Stage 5: Scale & Operations
      • Architecture
      • Observability
      • Load shedding
    • Stage 6: Security & Abuse
      • Controls
      • Abuse
    • Final Review Checklist
    • Tips for Effective Guidance
    • Handling Deviations
  • 项目或源文件

相关 Skill

更多
WebSocket WebSocket 实现可靠WebSocket连接,含重连、心跳与扩展支持。
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...