Agent SkillsJeffallan/claude-skills › websocket-engineer

websocket-engineer

GitHub

指导构建基于WebSocket/Socket.IO的实时通信系统,涵盖架构设计、水平扩展(Redis)、房间管理、鉴权及监控验证全流程。

skills/websocket-engineer/SKILL.md Jeffallan/claude-skills

Trigger Scenarios

需要实现双向实时消息传输 设计WebSocket集群与Redis适配方案 处理连接存在性与房间管理逻辑

Install

npx skills add Jeffallan/claude-skills --skill websocket-engineer -g -y
More Options

Use without installing

npx skills use Jeffallan/claude-skills@websocket-engineer

指定 Agent (Claude Code)

npx skills add Jeffallan/claude-skills --skill websocket-engineer -a claude-code -g -y

安装 repo 全部 skill

npx skills add Jeffallan/claude-skills --all -g -y

预览 repo 内 skill

npx skills add Jeffallan/claude-skills --list

SKILL.md

Frontmatter
{
    "name": "websocket-engineer",
    "license": "MIT",
    "metadata": {
        "role": "specialist",
        "scope": "implementation",
        "author": "https:\/\/github.com\/Jeffallan",
        "domain": "api-architecture",
        "version": "1.1.0",
        "triggers": "WebSocket, Socket.IO, real-time communication, bidirectional messaging, pub\/sub, server push, live updates, chat systems, presence tracking",
        "output-format": "code",
        "related-skills": "fastapi-expert, nestjs-expert, devops-engineer, monitoring-expert, security-reviewer"
    },
    "description": "Use when building real-time communication systems with WebSockets or Socket.IO. Invoke for bidirectional messaging, horizontal scaling with Redis, presence tracking, room management."
}

WebSocket Engineer

Core Workflow

  1. Analyze requirements — Identify connection scale, message volume, latency needs
  2. Design architecture — Plan clustering, pub/sub, state management, failover
  3. Implement — Build WebSocket server with authentication, rooms, events
  4. Validate locally — Test connection handling, auth, and room behavior before scaling (e.g., npx wscat -c ws://localhost:3000); confirm auth rejection on missing/invalid tokens, room join/leave events, and message delivery
  5. Scale — Verify Redis connection and pub/sub round-trip before enabling the adapter; configure sticky sessions and confirm with test connections across multiple instances; set up load balancing
  6. Monitor — Track connections, latency, throughput, error rates; add alerts for connection-count spikes and error-rate thresholds

Reference Guide

Load detailed guidance based on context:

Topic Reference Load When
Protocol references/protocol.md WebSocket handshake, frames, ping/pong, close codes
Scaling references/scaling.md Horizontal scaling, Redis pub/sub, sticky sessions
Patterns references/patterns.md Rooms, namespaces, broadcasting, acknowledgments
Security references/security.md Authentication, authorization, rate limiting, CORS
Alternatives references/alternatives.md SSE, long polling, when to choose WebSockets

Code Examples

Server Setup (Socket.IO with Auth and Room Management)

import { createServer } from "http";
import { Server } from "socket.io";
import { createAdapter } from "@socket.io/redis-adapter";
import { createClient } from "redis";
import jwt from "jsonwebtoken";

const httpServer = createServer();
const io = new Server(httpServer, {
  cors: { origin: process.env.ALLOWED_ORIGIN, credentials: true },
  pingTimeout: 20000,
  pingInterval: 25000,
});

// Authentication middleware — runs before connection is established
io.use((socket, next) => {
  const token = socket.handshake.auth.token;
  if (!token) return next(new Error("Authentication required"));
  try {
    socket.data.user = jwt.verify(token, process.env.JWT_SECRET);
    next();
  } catch {
    next(new Error("Invalid token"));
  }
});

// Redis adapter for horizontal scaling
const pubClient = createClient({ url: process.env.REDIS_URL });
const subClient = pubClient.duplicate();
await Promise.all([pubClient.connect(), subClient.connect()]);
io.adapter(createAdapter(pubClient, subClient));

io.on("connection", (socket) => {
  const { userId } = socket.data.user;
  console.log(`connected: ${userId} (${socket.id})`);

  // Presence: mark user online
  pubClient.hSet("presence", userId, socket.id);

  socket.on("join-room", (roomId) => {
    socket.join(roomId);
    socket.to(roomId).emit("user-joined", { userId });
  });

  socket.on("message", ({ roomId, text }) => {
    io.to(roomId).emit("message", { userId, text, ts: Date.now() });
  });

  socket.on("disconnect", () => {
    pubClient.hDel("presence", userId);
    console.log(`disconnected: ${userId}`);
  });
});

httpServer.listen(3000);

Client-Side Reconnection with Exponential Backoff

import { io } from "socket.io-client";

const socket = io("wss://api.example.com", {
  auth: { token: getAuthToken() },
  reconnection: true,
  reconnectionAttempts: 10,
  reconnectionDelay: 1000,       // initial delay (ms)
  reconnectionDelayMax: 30000,   // cap at 30 s
  randomizationFactor: 0.5,      // jitter to avoid thundering herd
});

// Queue messages while disconnected
let messageQueue = [];

socket.on("connect", () => {
  console.log("connected:", socket.id);
  // Flush queued messages
  messageQueue.forEach((msg) => socket.emit("message", msg));
  messageQueue = [];
});

socket.on("disconnect", (reason) => {
  console.warn("disconnected:", reason);
  if (reason === "io server disconnect") socket.connect(); // manual reconnect
});

socket.on("connect_error", (err) => {
  console.error("connection error:", err.message);
});

function sendMessage(roomId, text) {
  const msg = { roomId, text };
  if (socket.connected) {
    socket.emit("message", msg);
  } else {
    messageQueue.push(msg); // buffer until reconnected
  }
}

Constraints

MUST DO

  • Use sticky sessions for load balancing (WebSocket connections are stateful — requests must route to the same server instance)
  • Implement heartbeat/ping-pong to detect dead connections (TCP keepalive alone is insufficient)
  • Use rooms/namespaces for message scoping rather than filtering in application logic
  • Queue messages during disconnection windows to avoid silent data loss
  • Plan connection limits per instance before scaling horizontally

MUST NOT DO

  • Store large state in memory without a clustering strategy (use Redis or an external store)
  • Mix WebSocket and HTTP on the same port without explicit upgrade handling
  • Forget to handle connection cleanup (presence records, room membership, in-flight timers)
  • Skip load testing before production — connection-count spikes behave differently from HTTP traffic spikes

Output Templates

When implementing WebSocket features, provide:

  1. Server setup (Socket.IO/ws configuration)
  2. Event handlers (connection, message, disconnect)
  3. Client library (connection, events, reconnection)
  4. Brief explanation of scaling strategy

Knowledge Reference

Socket.IO, ws, uWebSockets.js, Redis adapter, sticky sessions, nginx WebSocket proxy, JWT over WebSocket, rooms/namespaces, acknowledgments, binary data, compression, heartbeat, backpressure, horizontal pod autoscaling

Documentation

Version History

  • 882ef55 Current 2026-08-20 09:05

Same Skill Collection

skills/angular-architect/SKILL.md
skills/api-designer/SKILL.md
skills/atlassian-mcp/SKILL.md
skills/chaos-engineer/SKILL.md
skills/cli-developer/SKILL.md
skills/cloud-architect/SKILL.md
skills/code-documenter/SKILL.md
skills/cpp-pro/SKILL.md
skills/csharp-developer/SKILL.md
skills/database-optimizer/SKILL.md
skills/debugging-wizard/SKILL.md
skills/django-expert/SKILL.md
skills/dotnet-core-expert/SKILL.md
skills/embedded-systems/SKILL.md
skills/fastapi-expert/SKILL.md
skills/feature-forge/SKILL.md
skills/flutter-expert/SKILL.md
skills/golang-pro/SKILL.md
skills/graphql-architect/SKILL.md
skills/java-architect/SKILL.md
skills/javascript-pro/SKILL.md
skills/kotlin-specialist/SKILL.md
skills/kubernetes-specialist/SKILL.md
skills/laravel-specialist/SKILL.md
skills/legacy-modernizer/SKILL.md
skills/mcp-developer/SKILL.md
skills/microservices-architect/SKILL.md
skills/nextjs-developer/SKILL.md
skills/pandas-pro/SKILL.md
skills/php-pro/SKILL.md
skills/playwright-expert/SKILL.md
skills/postgres-pro/SKILL.md
skills/python-pro/SKILL.md
skills/rag-architect/SKILL.md
skills/react-expert/SKILL.md
skills/react-native-expert/SKILL.md
skills/salesforce-developer/SKILL.md
skills/security-reviewer/SKILL.md
skills/spark-engineer/SKILL.md
skills/spring-boot-engineer/SKILL.md
skills/sre-engineer/SKILL.md
skills/swift-expert/SKILL.md
skills/terraform-engineer/SKILL.md
skills/the-fool/SKILL.md
skills/typescript-pro/SKILL.md
skills/vue-expert/SKILL.md
skills/architecture-designer/SKILL.md
skills/code-reviewer/SKILL.md
skills/devops-engineer/SKILL.md

Metadata

Files
0
Version
882ef55
Hash
3557582d
Indexed
2026-08-20 09:05

- 위키
Copyright © 2011-2026 iteam. Current version is 2.155.2. UTC+08:00, 2026-08-21 10:42
浙ICP备14020137号-1 $방문자$